如何操作字符串中间的文本?

时间:2018-10-06 14:19:59

标签: python string primitive

如何使用Python在特定索引处将字符串中的单词连接起来?
例如:-在字符串中,

"Delhi is the capital of India." 

我需要在“ the”之前和之后连接'123'

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

1 个答案:

答案 0 :(得分:1)

您可以使用str.replace().split()enumerate()来完成

使用 str.replace()

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

使用 .split() enumerate()

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()生成器表达式

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

进一步阅读

https://docs.python.org/3/library/stdtypes.html#string-methods https://en.m.wikipedia.org/wiki/Scunthorpe_problem