【问题标题】:python remove all text between first and second comma in string [closed]python删除字符串中第一个和第二个逗号之间的所有文本[关闭]
【发布时间】:2021-12-22 05:27:32
【问题描述】:

我有一个这样的字符串

gas,buck,12345,10fifty

我怎样才能得到这个字符串?

gas,,12345,10fifty

【问题讨论】:

  • 你需要澄清你的意图。您想知道如何删除逗号分隔列表的第二个元素吗?删除所有出现的“buck”?

标签: python


【解决方案1】:

一种选择可能是使用splitjoin 的列表推导,尽管它可能效率低:

s = "gas,buck,12345,10fifty"

output = ",".join("" if i == 1 else x for i, x in enumerate(s.split(",")))
print(output) # gas,,12345,10fifty

或者,在这种特定情况下,您可以使用re

output = re.sub(',.*?,', ',,', s, count=1)
print(output) # gas,,12345,10fifty

【讨论】:

    【解决方案2】:

    你可以使用str.<b>find</b>:

    >>> s = 'gas,buck,12345,10fifty'
    >>> first_comma_idx = s.find(',')
    >>> second_comma_idx = s.find(',', first_comma_idx)
    >>> s = s[:first_comma_idx+1] + s[second_comma_idx:]
    >>> s
    'gas,,buck,12345,10fifty'
    

    【讨论】:

      【解决方案3】:

      您可以使用带有re.sub 的正则表达式,最大替换为 1:

      import re
      s = 'gas,buck,12345,10fifty'
      re.sub(',.*?,', ',,', s, count=1)
      

      输出:'gas,,12345,10fifty'

      更好的例子
      import re
      s = 'a,b,c,d,e,f,g,h'
      re.sub(',.*?,', ',,', s, count=1)
      # 'a,,c,d,e,f,g,h'
      

      【讨论】:

        【解决方案4】:

        你可以尝试像这样替换你的字符串:

        your_string = "gas,buck,12345,10fifty"
        your_string = your_string.replace("buck", "")
        print(your_string)
        

        输出:

        gas,, 12345, 10fifty
        

        【讨论】:

        • 如果第二个元素中的字符串未知怎么办?大概解决方案必须是动态的。
        • 哦,好的。我想你可以使用re,但我认为他们已经有了答案here
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多