如何用Python来进行查询和替换一个文本字符串

如题所述

1、说明
可以使用find或者index来查询字符串,可以使用replace函数来替换字符串。
2、示例
1)查询
>>> 'abcdefg'.find('cde')
结果为2
'abcdefg'.find('acde')
结果为-1
'abcdefg'.index('cde')
结果为2
2)替换
'abcdefg'.replace('abc','cde')
结果为'cdedefg'
3、函数说明
1)find(...)
S.find(sub[, start[, end]]) -> int
返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可选的 参数start和end解释为切片表示法。
失败时返回-1。
2)index(...)
S.index(sub[, start[, end]]) -> int
与find函数类似,但是当未找到子字符串时引发ValueError。
3)replace(...)
S.replace(old, new[, count]) -> str
返回S的所有出现的子串的副本旧换新。 如果可选参数计数为给定,只有第一个计数出现被替换。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-11-09
1、说明
可以使用find或者index来查询字符串,可以使用replace函数来替换字符串。
2、示例
1)查询
>>> 'abcdefg'.find('cde')
结果为2
'abcdefg'.find('acde')
结果为-1
'abcdefg'.index('cde')
结果为2
2)替换
'abcdefg'.replace('abc','cde')
结果为'cdedefg'
3、函数说明
1)find(...)
S.find(sub[, start[, end]]) -> int
返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可选的 参数start和end解释为切片表示法。
失败时返回-1。
2)index(...)
S.index(sub[, start[, end]]) -> int
与find函数类似,但是当未找到子字符串时引发ValueError。
3)replace(...)
S.replace(old, new[, count]) -> str
返回S的所有出现的子串的副本旧换新。 如果可选参数计数为给定,只有第一个计数出现被替换。
第2个回答  2017-11-18
find()方法可以在一个较长的字符串中查找子串,返回子串坐在位置的最左端索引
replace()方法返回某字符串的所有匹配项均被替换之后得到的字符串
可能这里问的是正则表达式的东西!!!
可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])
replacement是被替换成的文本
string是需要被替换的文本
count是一个可选参数,指最大被替换的数量
例子:
import re
p = re.compile(‘(blue|white|red)’)
print(p.sub(‘colour’,'blue socks and red shoes’))
print(p.sub(‘colour’,'blue socks and red shoes’, count=1))
输出:
colour socks and colour shoes
colour socks and red shoes
subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量
例如:
import re
p = re.compile(‘(blue|white|red)’)
print(p.subn(‘colour’,'blue socks and red shoes’))
print(p.subn(‘colour’,'blue socks and red shoes’, count=1))
输出
(‘colour socks and colour shoes’, 2)
(‘colour socks and red shoes’, 1)本回答被提问者采纳
相似回答