我做的是我想做的事情(拿一个文件,把单词的中间字母重新加入其中),但是由于某种原因,这些空格被移除了,尽管我要求它在空格上拆分。为什么会这样呢?
import random
File_input= str(input("Enter file name here:"))
text_file=None
try:
text_file = open(File_input)
except FileNotFoundError:
print ("Please check file name.")
if text_file:
for line in text_file:
for word in line.split(' '):
words=list (word)
Internal = words[1:-1]
random.shuffle(Internal)
words[1:-1]=Internal
Shuffled=' '.join(words)
print (Shuffled, end='')发布于 2013-10-13 02:00:54
如果希望分隔符作为值的一部分:
d = " " #delim
line = "This is a test" #string to split, would be `line` for you
words = [e+d for e in line.split(d) if e != ""]这样做是拆分字符串,但返回拆分值加上使用的分隔符。结果仍然是一个列表,在本例中是['This ', 'is ', 'a ', 'test ']。
如果希望将分隔符作为结果列表的一部分,而不是使用常规的str.split(),则可以使用re.split()。医生注意到:
Re.split(模式,字符串,maxsplit=0,flags=0) 将字符串按模式出现的情况拆分。如果在模式中使用捕获括号,则模式中所有组的文本也将作为结果列表的一部分返回。
所以,你可以用:
import re
re.split("( )", "This is a test")结果:['this', ' ', 'is', ' ', 'a', ' ', 'test']
https://stackoverflow.com/questions/19341009
复制相似问题