【发布时间】:2020-07-13 19:12:03
【问题描述】:
我目前正在尝试复制拆分功能。我环顾四周,发现一个有很大帮助的,代码的唯一问题是空字符串没有显示为空,而是它们有多个撇号用于多个不同的空字符串。当前代码是
def mysplit(strng):
words = []
current_word = " "
for char in strng:
if char == " ":
words.append(current_word)
current_word = ""
else:
current_word += char
words.append(current_word)
return words
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
输出的结果
[' To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
[' To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[' ', '', '', '']
[' ', 'abc', '']
[' ']
我正在尝试得到结果
['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]
【问题讨论】:
-
您需要使用空字符串而不是空格来初始化
current_word。然后,如果您只在 current_word 不为空时追加到words,您应该获得您正在寻找的内容(这并不是 split() 的工作方式)
标签: python