jbl*_*u09 58 python string replace
我有这样的事情:
text = 'This text is very very long.'
replace_words = ['very','word']
for word in replace_words:
text = text.replace('very','not very')
Run Code Online (Sandbox Code Playgroud)
我想只替换第一个'非常'或选择哪个'非常'被覆盖.我在更大量的文本上这样做,所以我想控制重复单词的替换方式.
Fre*_*urk 94
text = text.replace("very", "not very", 1)
Run Code Online (Sandbox Code Playgroud)
>>> 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.
Run Code Online (Sandbox Code Playgroud)
Has*_*aza 31
text = text.replace("very", "not very", 1)
Run Code Online (Sandbox Code Playgroud)
第三个参数是要替换的最大出现次数.
从Python的文档:
string.replace(s,old,new [,maxreplace])
返回字符串s的副本,其中所有出现的substring old都替换为new.如果给出了可选参数maxreplace,则替换第一个maxreplace事件.
来自http://docs.python.org/release/2.5.2/lib/string-methods.html:
replace( old, new[, count])
返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换。如果给出了可选参数计数,则仅替换第一个计数出现。
我没有尝试,但我相信它有效
| 归档时间: |
|
| 查看次数: |
48891 次 |
| 最近记录: |