gpt4 book ai didi

python - 我应该在 Python 中使用正则表达式吗

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:01 25 4
gpt4 key购买 nike

我有这样一个字符串:

'cathy is a singer on fridays'

而且我希望能够用其他动词替换第四个词

所以

'cathy is a dancer on fridays'

我假设正确的方法是使用正则表达式并在到达第三个空格时停止,但您可以使用正则表达式和接受任何字符的 * 进行分组。我似乎无法让它工作。

任何建议都会有用。我是 Python 的新手,所以请不要评判。正则表达式是否也适用于此,还是我应该使用其他方法?

谢谢

最佳答案

不,这不需要正则表达式。见下文:

>>> mystr = 'cathy is a singer on fridays'
>>> x = mystr.split()
>>> x
['cathy', 'is', 'a', 'singer', 'on', 'fridays']
>>> x[3] = "dancer"
>>> x
['cathy', 'is', 'a', 'dancer', 'on', 'fridays']
>>> " ".join(x)
'cathy is a dancer on fridays'

或者,更紧凑:

>>> mystr = 'cathy is a singer on fridays'
>>> x = mystr.split()
>>> " ".join(x[:3] + ["dancer"] + x[4:])
'cathy is a dancer on fridays'
>>>

这里的核心原则是.split字符串的方法。

关于python - 我应该在 Python 中使用正则表达式吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19527924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com