题目
写一个去除字符串左边空格,右边空格,字符串中如果出现多个空格,则合并成一个空格的程序。
分析
用Python和C来解这道题的思路是不一样的,C的思路基本就是指针的移动,而Python有很多现成的东西可以用。
def simplify(text, space=" \t\r\n\f", delete=""):
result = []
word = ""
for char in text:
if char in delete:
continue
elif char in space:
if word: # 如果word为None,则说明是字符串开始,此时遇到
# 的空格直接忽略
result.append(word) # 如果word为True,则说明是中
# 间的空格,此时一个单词已经结
# 束,将其放入结果列表中
word = "" # 重置这个临时存储的单词
else:
word += char
if word:
result.append(word)
return " ".join(result) # 在最后为单词间添加空格
更为Pythonic的写法:
def simplified(text, delete=""):
result = []
word = []
for char in text:
if char in delete:
continue
elif char.isspace():
if word:
result.append("".join(word))
word = []
else:
word.append(char)
if word:
result.append("".join(word))
return " ".join(result)
主要的改变有临时变量word改为列表,判断是否为空字符或制表符等采用了isspace方法。
代码均来自于《Rapid Gui Programming with PyQt》.