Think before you speak, read before you think.

python str字符串处理

几个实际的例子

string = “abc”

字符串的长度
len(string)

转换为小写
string.lower()

转换为大写
string.upper()

统计字符串里一个字母a出现的次数

string.count(‘a’)

查找子串在一个字符串出现的位置,从0开始算,如果没找到返回-1

>>> string = ‘i love you’
>>> string.find(‘love’)
2

转换int to str

>>> a = 2

>>> type(a)

<type ‘int’>

>>> str(a)

‘2’

将字符串中的替换

.replace(‘:’,’’)

sum([bin(int(x)).count(‘1’) for x in ‘255.255.255.224’.split(‘.’)])

strip和split

strip() #removes from both ends

lstrip() #removes leading characters (Left-strip)

rstrip() #removes trailing characters (Right-strip)

>>> s = ‘ i love you ‘
>>> print s.strip()
i love you
>>> print s.lstrip()
i love you
>>> print s.rstrip()
i love you
>>> help(” abc”.strip)
>>> help(“abc”.split)


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *