【问题标题】:Python3 look for characters in a list and remove/add spacePython3 在列表中查找字符并删除/添加空格
【发布时间】:2020-06-22 08:40:43
【问题描述】:

我有一个列表,我正在尝试查看每个项目中的特定字符并删除它之前和之后的所有空格(如果有的话),然后在字符之后添加一个空格。我编写此代码的尝试失败了,因此我编写了一些 sudo 代码,希望它更有意义。

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

【问题讨论】:

  • 你能明确指定预期的输出吗?
  • 你可以使用re模块,或者更复杂的for循环

标签: python-3.x string list


【解决方案1】:

这可以工作:

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)

在这里找到一些非常有用的帮助:http://programmaticallyspeaking.com/split-on-separator-but-keep-the-separator-in-python.html

【讨论】:

    【解决方案2】:

    您可以使用正则表达式(特别是 re.sub)来执行此操作,以查找与您的字符之间的空格的任何匹配项,并将它们替换为仅字符和单个空格,如下所示:

    import re
    
    check_char = ":.,"
    regex_pattern = r'\s*(:|\.|,)\s*'
    
    list = [
        'This : is;a:string. yep!.',
        'This,is another , string']
    
    result = [re.sub(regex_pattern, r'\1 ', item) for item in list]
    print(result)
    

    输出:['This: is;a: string. yep!. ', 'This, is another, string']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2020-10-14
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多