【问题标题】:Python remove from beginning to first specific character in a string? [duplicate]Python从字符串中的开头到第一个特定字符删除? [复制]
【发布时间】:2020-02-13 03:35:55
【问题描述】:

假设我有以下字符串:

this is ;a cool test

如何删除从启动到第一次出现; 的所有内容? 预期输出为a cool test

我只知道如何使用括号表示法删除固定数量的字符,这在这里没有帮助,因为;的位置不固定。

【问题讨论】:

    标签: python string split


    【解决方案1】:

    使用str.find 和切片。

    例如:

    s = "this is ;a cool test; Hello World."
    print(s[s.find(";")+1:])
    # --> a cool test; Hello World.
    

    或使用str.split

    例如:

    s = "this is ;a cool test; Hello World."
    print(s.split(";", 1)[-1])
    # --> a cool test; Hello World.
    

    【讨论】:

      【解决方案2】:

      你可以使用正则表达式

      import re
      x = "this is ;a cool test"
      x = re.sub(r'^[^;]+;','',x)
      print(x)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-22
        • 2022-11-28
        • 1970-01-01
        相关资源
        最近更新 更多