regex 消除字符串中除字符串末尾以外的白色

csbfibhn  于 2023-01-06  发布在  其他
关注(0)|答案(3)|浏览(151)

我想消除字符串中除字符串末尾以外的空格
代码:

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 ']
eblbsuwk

eblbsuwk1#

我们可以先去掉开头/结尾的空格,然后用逗号替换空格:

import re

sentence = ['He must be having a great time\n                           ', 'It is fun to play chess      ', 'Sometimes TT is better than Badminton             ']
output = [re.sub(r'\s+', ',', x.strip()) for x in sentence]
print(output)

这将打印:

['He,must,be,having,a,great,time',
 'It,is,fun,to,play,chess',
 'Sometimes,TT,is,better,than,Badminton']
qco9c6ql

qco9c6ql2#

您可以使用更简单的split/join方法(时间:1.48微秒± 74纳秒)。
str.split()将按空格字符组(例如空格或换行符)进行拆分。
str.join(iter)将把iter的元素与它所使用的字符串连接起来。
演示:

sentence = [
    "He must be having a great time\n                           ",
    "It is fun to play chess      ",
    "Sometimes TT is better than Badminton             ",
]
[",".join(s.split()) for s in sentence]

给予

['He,must,be,having,a,great,time',
 'It,is,fun,to,play,chess',
 'Sometimes,TT,is,better,than,Badminton']

第二种方法,strip/replace(时间:1.56微秒± 107纳秒)。
str.strip()删除str开头和结尾的所有空白字符。
str.replace(old, new)将str中所有出现的old替换为new(之所以有效,是因为字符串中的单词之间只有一个空格)。
演示:

sentence = [
    "He must be having a great time\n                           ",
    "It is fun to play chess      ",
    "Sometimes TT is better than Badminton             ",
]

[s.strip().replace(" ", ",") for s in sentence]

给予

['He,must,be,having,a,great,time',
 'It,is,fun,to,play,chess',
 'Sometimes,TT,is,better,than,Badminton']
ki0zmccv

ki0zmccv3#

def eliminating_white_spaces(list):
for string in range(0,len(list)):
    if ' ' in list[string] and string+1==len(list):
        pass
    else:  
        list[string]=str(list[string]).replace(' ',',')
return list

相关问题