我想消除字符串中除字符串末尾以外的空格
代码:
sentence = ['He must be having a great time/n ', 'It is fun to play chess ', 'Sometimes TT is better than Badminton ']
pattern = "\s+^[\s+$]"
res = [re.sub(pattern,', ', line) for line in sentence]
print(res)
但是...
输出与输入列表相同。
['He must be having a great time/n ', 'It is fun to play chess ', 'Sometimes TT is better than Badminton ']
谁能提出正确的解决办法。
代码:
sentence = ['He must be having a great time ', 'It is fun to play chess ', 'Sometimes TT is better than Badminton ']
pattern = "\s+^[\s+$]"
res = [re.sub(pattern,', ', line) for line in sentence]
print(res)
但是...
输出与输入列表相同。
['He must be having a great time/n ', 'It is fun to play chess ', 'Sometimes TT is better than Badminton ']
预期产出:
['He,must,be,having,a,great,time', 'It,is,fun,to,play,chess', 'Sometimes,TT,is,better,than,Badminton ']
3条答案
按热度按时间eblbsuwk1#
我们可以先去掉开头/结尾的空格,然后用逗号替换空格:
这将打印:
qco9c6ql2#
您可以使用更简单的
split/join
方法(时间:1.48微秒± 74纳秒)。str.split()
将按空格字符组(例如空格或换行符)进行拆分。str.join(iter)
将把iter的元素与它所使用的字符串连接起来。演示:
给予
第二种方法,
strip/replace
(时间:1.56微秒± 107纳秒)。str.strip()
删除str开头和结尾的所有空白字符。str.replace(old, new)
将str中所有出现的old
替换为new
(之所以有效,是因为字符串中的单词之间只有一个空格)。演示:
给予
ki0zmccv3#