簡體   English   中英

Python:替換字符串中的第n個單詞

[英]Python: replace nth word in string

假設每個單詞用空格分隔,用Python替換字符串中第n個單詞的最簡單方法是什么? 例如,如果我想替換字符串的第十個單詞並獲取結果字符串。

我想你可能會這樣做:

nreplace=1
my_string="hello my friend"
words=my_string.split(" ")
words[nreplace]="your"
" ".join(words)

這是另一種替換方式:

nreplace=1
words=my_string.split(" ")
" ".join([words[word_index] if word_index != nreplace else "your" for word_index in range(len(words))])

假設你的字符串是:

my_string = "This is my test string."

您可以使用split(' ')拆分字符串

my_list = my_string.split()

my_list設置為

['This', 'is', 'my', 'test', 'string.']

您可以使用替換第4個列表項

my_list[3] = "new"

然后把它放回去

my_new_string = " ".join(my_list)

給你

"This is my new string."

涉及列表理解的解決方案:

text = "To be or not to be, that is the question"
replace = 6
replacement = 'it'
print ' '.join([x if index != replace else replacement for index,x in enumerate(s.split())])

以上產生:

To be or not to be, it is the question

您可以使用生成器表達式和字符串join()方法:

my_string = "hello my friend"
nth = 0
new_word = 'goodbye'

print(' '.join(word if i != nth else new_word
                for i, word in enumerate(my_string.split(' '))))

輸出:

goodbye my friend

通過re.sub。

>>> import re
>>> my_string = "hello my friend"
>>> new_word = 'goodbye'
>>> re.sub(r'^(\s*(?:\S+\s+){0})\S+', r'\1'+new_word, my_string)
'goodbye my friend'
>>> re.sub(r'^(\s*(?:\S+\s+){1})\S+', r'\1'+new_word, my_string)
'hello goodbye friend'
>>> re.sub(r'^(\s*(?:\S+\s+){2})\S+', r'\1'+new_word, my_string)
'hello my goodbye'

只需將花括號內的數字替換為您要替換的單詞的位置 - 1.即,為了替換第一個單詞,數字將為0 ,對於第二個單詞,數字將為1,同樣繼續。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM