Как манипулировать текстом в середине строки? - PullRequest
0 голосов
/ 06 октября 2018

Как я могу объединить слово в строке с определенным индексом, используя Python?
Например: - В строке

"Delhi is the capital of India." 

Мне нужно объединить '123' до и после '.

Выходные данные должны быть: - "Delhi is 123the123 capital of India."

1 Ответ

0 голосов
/ 06 октября 2018

Вы можете использовать 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

...