python字符串操作方法大全(替换、删除、截取、复制、连接、比较、查找等)

发布时间:2019-11-04编辑:脚本学堂
python字符串操作实例大汇总,包括了几乎所有常用的python字符串操作,如字符串的替换、删除、截取、复制、连接、比较、查找、分割等。有需要的朋友不要错过。
扫描字符串
 

复制代码 代码示例:
#strpbrk(sStr1,sStr2)
sStr1 = 'cekjgdklab'
sStr2 = 'gka'
nPos = -1
for c in sStr1:
    if c in sStr2:
        nPos = sStr1.index(c)
        break
print nPos

翻转字符串
 

复制代码 代码示例:
#strrev(sStr1)
sStr1 = 'abcdefg'
sStr1 = sStr1[::-1]
print sStr1

查找字符串
 

复制代码 代码示例:
#strstr(sStr1,sStr2)
sStr1 = 'abcdefg'
sStr2 = 'cde'
print sStr1.find(sStr2)

分割字符串
 

复制代码 代码示例:
#strtok(sStr1,sStr2)
sStr1 = 'ab,cde,fgh,ijk'
sStr2 = ','
sStr1 = sStr1[sStr1.find(sStr2) + 1:]
print sStr1
#或
s = 'ab,cde,fgh,ijk'
print(s.split(','))

连接字符串
 

复制代码 代码示例:
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)

PHP 中 addslashes 的实现
 

复制代码 代码示例:
def addslashes(s):
    d = {'"':'"', "'":"'", "":"", "":"\"}
    return ''.join(d.get(c, c) for c in s)
 
s = "John 'Johny' Doe (a.k.a. "Super Joe")"
print s
print addslashes(s)

只显示字母与数字
 

复制代码 代码示例:
def OnlyCharNum(s,oth=''):
    s2 = s.lower();
    fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
    for c in s2:
        if not c in fomart:
            s = s.replace(c,'');
    return s;
 
print(OnlyStr("a000 aa-b"))