0

我有这个做我想做的事情(拿一个文件,打乱单词的中间字母并重新加入它们),但由于某种原因,即使我要求它在空格上拆分,空格也会被删除。这是为什么?

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='')
4

1 回答 1

1

如果您希望分隔符作为值的一部分:

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(pattern, string[, maxsplit=0, flags=0])
根据出现的模式分割字符串。如果在模式中使用捕获括号,则模式中所有组的文本也会作为结果列表的一部分返回。

所以,你可以使用:

import re
re.split("( )", "This is a test")

结果: ['this', ' ', 'is', ' ', 'a', ' ', 'test']

于 2013-10-13T02:00:54.103 回答