Python字符串

发布于 2017-07-03 · 本文总共 2223 字 · 阅读大约需要 7 分钟

字符串

ord(‘h’)----> 104

chr(100)  ----> 'd'

str1[::-1]:反序

str1.capitalize():首字母大写,其余小写

str1.title():

str1.centerwidth):居中,空格填充

str1.countsubstr,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

html

文本解析




本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表