Python 3.x Python3在列表中查找字符并删除/添加空格
我有一个列表,我试图在每个项目中查找特定的字符,并删除其前后的任何空格(如果有),然后在字符后添加空格。我尝试编写这段代码失败得很惨,所以我写了一些sudo代码,希望它更有意义Python 3.x Python3在列表中查找字符并删除/添加空格,python-3.x,string,list,Python 3.x,String,List,我有一个列表,我试图在每个项目中查找特定的字符,并删除其前后的任何空格(如果有),然后在字符后添加空格。我尝试编写这段代码失败得很惨,所以我写了一些sudo代码,希望它更有意义 check_char = ":.," list = [ 'This : is;a:string. yep!.' 'This,is another , string'] for item in list: # Look for character(s) in check_ch
check_char = ":.,"
list = [
'This : is;a:string. yep!.'
'This,is another , string']
for item in list:
# Look for character(s) in check_char
# remove white space before and after character
# add space after the character
这可能会起作用:
import re
check_char = ":.,"
list = [
'This : is;a:string. yep!.',
'This,is another , string']
for item in list:
splitted = re.split("(:|\.|,)", item)
stripped = [x.strip() for x in splitted]
whitespace = [x + ' ' if x in check_char else x for x in stripped]
joined = ''.join(whitespace)
print(joined)
此处提供了一些非常有用的帮助:您可以使用正则表达式来执行此操作,具体来说,您可以找到任何与空格匹配的字符,并将其替换为字符和单个空格,如下所示:
重新导入
选中_char=“:,”
regex\u pattern=r'\s*(:\.\124;,)\ s*'
列表=[
'This:is;a:string.yes!',
'这是另一个字符串']
结果=[re.sub(regex_模式,r'\1',item)用于列表中的项]
打印(结果)
输出:
['This:is;a:string.yep!。','This,is另一个,string']
您可以明确指定预期的输出吗?您可以使用re模块,或更复杂的for循环