Python 字符串操作

来源:互联网 发布:教育平台软件提供 编辑:程序博客网 时间:2024/06/03 07:00

转自:http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html

s.strip() .lstrip() .rstrip(',') 去空格及特殊符号

复制字符串

Python

1#strcpy(sStr1,sStr2)
2sStr1 ='strcpy'
3sStr2 =sStr1
4sStr1 ='strcpy2'
5print sStr2

连接字符串

Python

1#strcat(sStr1,sStr2)
2sStr1 ='strcat'
3sStr2 ='append'
4sStr1 +=sStr2
5print sStr1

查找字符

< 0 未找到

Python

1#strchr(sStr1,sStr2)
2sStr1 ='strchr'
3sStr2 ='s'
4nPos =sStr1.index(sStr2)
5print nPos

比较字符串

Python

1#strcmp(sStr1,sStr2)
2sStr1 ='strchr'
3sStr2 ='strch'
4print cmp(sStr1,sStr2)

扫描字符串是否包含指定的字符

Python

1#strspn(sStr1,sStr2)
2sStr1 ='12345678'
3sStr2 ='456'
4#sStr1 and chars both in sStr1 and sStr2
5print len(sStr1 and sStr2)

字符串长度

Python

1#strlen(sStr1)
2sStr1 ='strlen'
3print len(sStr1)

将字符串中的大小写转换

Python

1#strlwr(sStr1)
2sStr1 ='JCstrlwr'
3sStr1 =sStr1.upper()
4#sStr1 = sStr1.lower()
5print sStr1

追加指定长度的字符串

Python

1#strncat(sStr1,sStr2,n)
2sStr1 ='12345'
3sStr2 ='abcdef'
4n = 3
5sStr1 +=sStr2[0:n]
6print sStr1

字符串指定长度比较

Python

1#strncmp(sStr1,sStr2,n)
2sStr1 ='12345'
3sStr2 ='123bc'
4n = 3
5print cmp(sStr1[0:n],sStr2[0:n])

复制指定长度的字符

Python

1#strncpy(sStr1,sStr2,n)
2sStr1 =''
3sStr2 ='12345'
4n = 3
5sStr1 =sStr2[0:n]
6print sStr1

将字符串前n个字符替换为指定的字符

Python

1#strnset(sStr1,ch,n)
2sStr1 ='12345'
3ch = 'r'
4n = 3
5sStr1 =n * ch+ sStr1[3:]
6print sStr1

扫描字符串

Python

1#strpbrk(sStr1,sStr2)
2sStr1 ='cekjgdklab'
3sStr2 ='gka'
4nPos =-1
5for c in sStr1:
6if c in sStr2:
7nPos =sStr1.index(c)
8break
9print nPos

翻转字符串

Python

1#strrev(sStr1)
2sStr1 ='abcdefg'
3sStr1 =sStr1[::-1]
4print sStr1

查找字符串

Python

1#strstr(sStr1,sStr2)
2sStr1 ='abcdefg'
3sStr2 ='cde'
4print sStr1.find(sStr2)

分割字符串

Python

1#strtok(sStr1,sStr2)
2sStr1 ='ab,cde,fgh,ijk'
3sStr2 =','
4sStr1 =sStr1[sStr1.find(sStr2) +1:]
5print sStr1
6或者
7s = 'ab,cde,fgh,ijk'
8print(s.split(','))

连接字符串

Python

1delimiter =','
2mylist =['Brazil','Russia', 'India','China']
3print delimiter.join(mylist)

PHP 中 addslashes 的实现

Python

1def addslashes(s):
2d ={'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
3return''.join(d.get(c, c) for c in s)
4 
5s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0"
6print s
7print addslashes(s)

只显示字母与数字

Python

1def OnlyCharNum(s,oth=''):
2s2 =s.lower();
3fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
4for c in s2:
5if not c in fomart:
6s =s.replace(c,'');
7returns;
8 
9print(OnlyStr("a000 aa-b"))