只替换第一次出现的字符串? [英] Replace first occurrence only of a string?

查看:73
本文介绍了只替换第一次出现的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

text = '这段文字很长很长.'replace_words = ['very','word']对于 replace_words 中的单词:text = text.replace('非常','不是非常')

我只想替换第一个非常"或选择覆盖哪个非常".我正在对大量文本执行此操作,因此我想控制替换重复单词的方式.

解决方案

text = text.replace("very", "not very", 1)

<预><代码>>>>帮助(str.replace)关于 method_descriptor 的帮助:代替(...)S.replace (old, new[, count]) ->细绳返回字符串 S 的副本,其中包含所有出现的子字符串旧换新.如果可选参数计数是给定,只替换第一个计数出现.

I have something like this:

text = 'This text is very very long.'
replace_words = ['very','word']

for word in replace_words:
    text = text.replace('very','not very')

I would like to only replace the first 'very' or choose which 'very' gets overwritten. I'm doing this on much larger amounts of text so I want to control how duplicate words are being replaced.

解决方案

text = text.replace("very", "not very", 1)

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace (old, new[, count]) -> string

    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.

这篇关于只替换第一次出现的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆