如何使用Python在特定索引处将字符串中的单词连接起来?
例如:-在字符串中,
"Delhi is the capital of India."
我需要在“ the”之前和之后连接'123'
。
输出应为:-"Delhi is 123the123 capital of India."
答案 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