【问题标题】:Remove String between two characters for all occurrences删除所有出现的两个字符之间的字符串
【发布时间】:2020-09-06 04:15:59
【问题描述】:

我正在寻找有关 Python 3 中字符串操作的帮助。

输入字符串

s = "ID bigint,FIRST_NM string,LAST_NM string,FILLER1 string"

期望的输出

s = "ID,FIRST_NM,LAST_NM,FILLER1"

基本上,目标是删除输入字符串中所有出现的空格和逗号之间的任何内容。

非常感谢任何帮助

【问题讨论】:

标签: python python-3.x string replace


【解决方案1】:

使用简单的regex

import re
s = "ID bigint,FIRST_NM string,LAST_NM string,FILLER1 string"
res = re.sub('\s\w+', '', s)
print(res) 

# output ID,FIRST_NM,LAST_NM,FILLER1

【讨论】:

    【解决方案2】:

    你可以使用正则表达式

    import re
    
    s = "ID bigint,FIRST_NM string,LAST_NM string,FILLER1 string"
    s = ','.join(re.findall('\w+(?= \w+)', s))
    print(s)
    

    输出:

    ID,FIRST_NM,LAST_NM,FILLER1
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2015-07-23
      • 2016-07-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多