【问题标题】:Remove the first word in a string when this word equals to "the"当该单词等于“the”时,删除字符串中的第一个单词
【发布时间】:2019-09-20 17:28:47
【问题描述】:

我有一个字符串“西雅图市”或“纽约市”。我希望删除“the”这个词并将其转换为“city of Seattle”。如果字符串是“a city of Seattle”,它应该保持不变。

我尝试使用 python 正则表达式来解决问题,但失败了。我相信我的正则表达式不正确。

s = "the city of seattle"
s = s.replace(/^the /, '');
print s

s1 = "a city of seattle"
s1 = s1.replace(/^the /, '');
print s1

预期的结果是:“city of seattle”和“a city of seattle”,但出现语法错误。

【问题讨论】:

  • Python 没有正则表达式文字。请阅读the re module。 (另外,在未来,请包含准确的错误消息,而不仅仅是“语法错误”。您收到的可能包含有用的信息。请参阅How to Ask。)
  • 如果您在浏览器中搜索“Python 正则表达式教程”,您会找到比我们在此处管理的更能解释这一点的参考资料。
  • 您也可以使用startswith 方法来解决此问题。

标签: python regex string


【解决方案1】:

在 Python 中(假设您来自 JavaScript),正则表达式文字 只是字符串(括在引号中,而不是 /.../),替换正则表达式需要 re 模块(特别是re.sub 函数):

import re

s = "the city of seattle"
s = re.sub('^the ', '', s)
print s

s1 = "a city of seattle"
s1 = re.sub('^the ', '', s1)
print s1

输出:

city of seattle
a city of seattle

【讨论】:

  • 谢谢,应该是“'^the'”而不是“/^the/”
【解决方案2】:

不需要re的方法:

s = "the city of seattle"

word = "the"
if s.startswith(word):
    s = s[len(word):].lstrip()

print(s)
# "city of seattle"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2011-10-12
    • 2022-01-16
    相关资源
    最近更新 更多