[英]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.