关于python:如何操作字符串中间的文本?

How to manipulate text in the middle of a string?

如何使用python在特定索引的字符串中连接一个单词?例如:在字符串中,

1
"Delhi is the capital of India."

我需要在"the"前后连接'123'

输出应为-"Delhi is 123the123 capital of India."


您可以使用str.replace().split()enumerate()来完成此操作。

使用str.replace()

1
2
3
s ="Delhi is the capital of India."
s = s.replace('the', '123the123')
# Delhi is 123the123 capital of India.

使用.split()enumerate()

1
2
3
4
5
6
s ="Delhi is the capital of India."
s = s.split()
for i, v in enumerate(s):
    if v == 'the':
        s[i] = '123the123'
s = ' '.join(s)

带生成器表达式的' '.join()

1
print(' '.join("123the123" if w=="the" else w for w in s.split()))

进一步阅读

https://docs.python.org/3/library/stdtypes.html字符串方法https://en.m.wikipedia.org/wiki/scunthorpe_问题