【问题标题】:Cut string in Python from specific word/words to the end of the string [duplicate]将Python中的字符串从特定的单词/单词剪切到字符串的末尾[重复]
【发布时间】:2019-11-01 17:20:04
【问题描述】:

您好,我正在尝试从特定表达式中删除部分字符串。例如:

string = "Hello my name is John and I would like to eat pizza"
string.removeTillTheEnd(string, "John")

现在字符串将是Hello my name is

替换功能还不够……

【问题讨论】:

  • 使用正则表达式将是John.*$

标签: python regex python-3.x


【解决方案1】:

这个怎么样?

string = "Hello my name is John and I would like to eat pizza"
split_string = string.split("John", maxsplit=1)[0]

字符串上的split 方法将一个字符串拆分成一个列表,给定一个分隔符,然后我们取出找到的第一个元素。 maxsplit 参数仅用于分隔它找到的第一次出现的“John”。

【讨论】:

    【解决方案2】:

    不需要正则表达式或拆分成列表,只需找到位置和切片

    string = "Hello my name is John and I would like to eat pizza"
    string = string[:string.find('John')].strip()
    print(string)   # "Hello my name is"
    

    【讨论】:

      猜你喜欢
      • 2020-11-04
      • 2017-04-12
      • 1970-01-01
      • 2019-07-25
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多