现在我们看看python 中字符串有哪些功能
字符串的操作
下面我随意新建一个字符串,看看字符串可以进行哪些操作
>>> mystring='dsffklefji'
>>> dir(mystring)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
可以看到操作有好多,我选几个常用的操作看看使用效果如何。
count和len
count从字面上看就是数数,统计字符串中某元素的个数.len就是字符串的长度。
>>> mystring.count('s')
1
>>> len(mystring)
10
startwith,in,find和join
startwith(str)是查看是否以str开头,in是查看字符是否在字符串中,find是查找字符串中是否有某字符,有则返回第一个该字符的位置,join把列表中的每个元素用指定字符连接起来存成字符串。
#!/usr/bin/python
# Filename: str_methods.py
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') != -1:
print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
输出:
$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
split和strip
split用于在指定字符处分割字符串,并存储到列表中。
>>> mystring='we are happy'
>>> newstring=mystring.split(' ')
>>> print newstring
['we', 'are', 'happy']
strip用于把字符串前后指定的垃圾字符清除掉(从单词的意思看就是脱掉嘻嘻),还支持正则表达式
>>> mystring='+000%I have a dream%%%'
>>> import re
>>> mystring.strip(r'+0*')
'%I have a dream%%%'
>>> print mystring
'+000%I have a dream%%%'
括号里的r’+0*’表示这是一个正则表达式,把+0…0去掉。注意,这里的字符串改完之后原来的字符不会改变,除非赋值到一个变量中
>>> mystring='+000%I have a dream%%%'
>>> mystring=mystring.strip(r'+0*')
>>> mystring=mystring.strip('%')
>>> print mystring
I have a dream
字符串的格式化输出
前面已经用到过,这里对所有支持的格式化输出详细列出。形式如下的就叫字符串的格式化输出:
>>> print "My name is %s and weight is %d kg!" % ('Zara', 21)
My name is Zara and weight is 21 kg!
%后面加指定字符表示格式,具体输出格式列表如下:
符号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |