Python字符串
发布于 2017-07-03 · 本文总共 2223 字 · 阅读大约需要
7 分钟
字符串
ord(‘h’)----> 104
chr(100) ----> 'd'
str1[::-1]:反序
str1.capitalize():首字母大写,其余小写
str1.title():
str1.center(width):居中,空格填充
str1.count(substr,0,n)
str.decode()
str.encode()
str.endwith()
str.expandtabs()
str.find():返回第一个目标字符出现的位置,查找不到返回‘-1’
str.index():查找不到返回异常
str.isalnum():是否全是字母或数字
str.isalpha():是否全是字母
str.isdecimal():
str.isdigit():是否全是数字
str.islower():
str.isnumeric():
str.isspace():是否全是空白字符,并至少有一个字符
str.istitle()
大小写
str.isupper()
str.swapcase():大小写互换
str.lower()
字符串连接
str.join(seq):把seq序列用str连接起来
>>> print "#".join("bcdefg")
b#c#d#e#f#g
去空格
str.strip()
str.lstrip()
字符串替换
str.replace(old,new)
字符串分割
str.split()
str.splitlinres([keepends]):按行分割符分为一个list
类型转换
import string
str.atoi(s1,10)
str.atoi(s1,16)
str.atol(s)
str.atof(s,base)
字符串拆分-re.split
>>> line = "afdhhjfdj hfjd; fhjd, fjhjdf, jfhjh;"
>>> import re
>>> re.split(r'[;,\s]\s*', line)
['afdhhjfdj', 'hfjd', 'fhjd', 'fjhjdf', 'jfhjh', '']
>>> re.split(r'(;|,|\s)\s*', line)
['afdhhjfdj', ' ', 'hfjd', ';', 'fhjd', ',', 'fjhjdf', ',', 'jfhjh', ';', '']
>>> re.split(r'(?:;|,|\s)\s*', line)
['afdhhjfdj', 'hfjd', 'fhjd', 'fjhjdf', 'jfhjh', '']
首尾判断-str.startswith
str.startswith(substr):是否以substr开头
str.endswith(substr):是否以substr结尾
str.startswith(tuple([“xxx”, “xxxxxx”]))
利用Shell通配符做字符串匹配
>>> import fnmatch
>>> fnmatch.fnmatch("foo.txt", "*.txt")
True
>>> fnmatch.fnmatch("foo.txt", "?.txt")
False
>>>
>>> fnmatch.fnmatch("foo.txt", "?oo.txt")
True
>>>
>>> fnmatch.fnmatch("foo1.txt", "foo[0-9].txt")
True
另外可用的模块glob
转换–translate
replist = string.maketrans(s,r) s到r的转换表
s.translate(replist)
string.capwords(s,seq=None):以seq分割后首字母大写
对齐
ljust,rjust字符对齐
str.ljust(width):向左对齐,右边补空格
str.rjust(width):向右对齐
str.zfill(width):右对齐,补0
format
>>> format("hello", "=^20")
'=======hello========'
>>> format("hello", "=<20")
'hello==============='
>>> format("hello", "=>20")
'===============hello'
多个字符串
>>> "{:>20s} {:<20s}".format("hello", "world")
' hello world '
>>>
>>>
>>>
>>> "{:=>20s} {:<20s}".format("hello", "world")
'===============hello world '
>>>
>>>
>>>
>>> "{:=>20s} {:=<20s}".format("hello", "world")
'===============hello world==============='
重新格式化
textwrap