去空格及特殊符号
s.strip().lstrip().rstrip(',') #去除开头或结尾的空格及特殊符号
var1=' hello world, 'print '"'+ var1 + '"' + ' strip('') is '+ '"' + var1.strip(' ') + '"'print '"'+ var1 + '"' + ' lstrip() is '+ '"' + var1.lstrip()+'"'print '"'+ var1 + '"' + ' rstrip() is '+ '"' + var1.rstrip()+'"'var2=' hello world,'print '"'+ var2 + '"' + ' rstrip(',') is '+ '"' + var2.rstrip(',')+'"'
var1=' hello world, 'print '"'+ var1 + '"' + ' strip('') is '+ '"' + var1.strip(' ') + '"'print '"'+ var1 + '"' + ' lstrip() is '+ '"' + var1.lstrip()+'"'print '"'+ var1 + '"' + ' rstrip() is '+ '"' + var1.rstrip()+'"'print '"'+ var1 + '"' + ' rstrip(',') is '+ '"' + var1.rstrip(',')+'"'" hello world, " strip() is "hello world,"" hello world, " lstrip() is "hello world, "" hello world, " rstrip() is " hello world,"" hello world, " rstrip( ) is " hello world, "
var2=' hello world,'print '"'+ var2 + '"' + ' rstrip(',') is '+ '"' + var2.rstrip(',')+'"'" hello world," rstrip( ) is " hello world"
复制字符串
#strcpy(sStr1,sStr2)sStr1 = 'strcpy'sStr2 = sStr1sStr1 = 'strcpy2'print sStr2strcpy
连接字符串
#strcat(sStr1,sStr2)
sStr1 = 'strcat'sStr2 = 'append'sStr1 += sStr2print sStr1
strcatappend
查找字符,返回字符串的位置(左边第一位为0,多个字符只返回第一个的位置)
#strchr(sStr1,sStr2)
# < 0 为未找到,或者 未找到为 ‘ValueError: substring not found’
sStr1 = 'strchr'sStr2 = 'r'#sStr3 = 'm'nPos = sStr1.index(sStr2)#mm = sStr1.index(sStr3)print nPos#print mm2
比较字符串,返回值只有0,1和-1,0为一样
sStr1 = 'strchr'sStr2 = 'strchr'print cmp(sStr1,sStr2)0
sStr1 = 'strchr'sStr2 = 'strch'print cmp(sStr1,sStr2)1
sStr1 = 'strchr'sStr2 = 'strche'print cmp(sStr1,sStr2)1
sStr1 = 'strchr'sStr2 = 'strcwe'print cmp(sStr1,sStr2)-1
sStr1 = 'strchr'sStr2 = 'strcw'print cmp(sStr1,sStr2)-1
sStr1 = 'strchr'sStr2 = 'strcw 'print cmp(sStr1,sStr2)-1
sStr1 = 'strchr'sStr2 = 'strcwrwe'print cmp(sStr1,sStr2)-1
sStr1 = 'strchr'sStr2 = 'strc'print cmp(sStr1,sStr2)1
扫描字符串是否包含指定的字符
sStr1 = '12345678'sStr2 = '456'#sStr1 and chars both in sStr1 and sStr2print len(sStr1 and sStr2)3
sStr1 = '12345678'sStr2 = '4567'#sStr1 and chars both in sStr1 and sStr2print len(sStr1 and sStr2)4
sStr1 = '12345678'sStr2 = '4567'#sStr1 and chars both in sStr1 and sStr2print sStr1 and sStr24567
字符串长度
sStr1 = 'strlen'print len(sStr1)6
将字符串中的大小写转换
sStr1 = 'JCstrlwr'sStr1 = sStr1.upper()#sStr1 = sStr1.lower()print sStr1JCSTRLWR
追加指定长度的字符串
sStr1 = '12345'sStr2 = 'abcdef'n = 3sStr1 += sStr2[0:n]print sStr112345abc
字符串指定长度比较
sStr1 = '12345'sStr2 = '123bc'n = 3print cmp(sStr1[0:n],sStr2[0:n])0
复制指定长度的字符
sStr1 = ''sStr2 = '12345'n = 3sStr1 = sStr2[0:n]print sStr1123
sStr1 = '1'sStr2 = '12345'n = 3sStr1 = sStr1+sStr2[0:n]print sStr11123
将字符串前n个字符替换为指定的字符
sStr1 = '12345'ch = 'r'n = 3sStr1 = n * ch + sStr1[3:]print sStr1rrr45
扫描字符串
sStr1 = 'cekjgdklab'
sStr2 = 'gka'
nPos = -1
for c in sStr1:
if c in sStr2:
nPos = sStr1.index(c)
break
print nPos
2
【此处需看for循环,未完待续/huangcong/archive//08/29/2158268.html】
Python 字符串(三)-字符串操作实例(string替换 删除 截取 复制 连接 比较 查找 包含 大小写转换 分割等)