字符串处理方法

来自CloudWiki
跳转至: 导航搜索

"方法"在编程中是一个专有名词 -"方法"特指<a>.()风格中的函数<b>() -字符串及变量也是<a>,存在一些方法

str.lower()或str.upper()
返回字符串的副本,全部字符小写/大写
"AbCdEfGh".lower()结果为"abcdefgh"

str.split(sep=None)
返回一个列表,由str根据sep被分隔的部分组成
"A,B,C".split(",")结果为['A','B','C']

str.count(sub)
返回子串sub在str中出现的次数
"a apple a day".count("a")结果为4

str.replace(old, new)
返回字符串str副本,所有old子串被替换为new
"python".replace(""n",""n123.io"")结果为"python123.io"

str.center(width[,fillchar])
字符串str根据宽度width居中,fillchar可选
"python".center(20,"=")结果为'=======python======'

str.strip(chars)
从str中去掉在其左侧和右侧chars中列出的字符 
"= python= ".strip(" =np")结果为"ytho"
 

str.join(iter)
在iter变量除最后元素外每个元素后增加一个str
", ".join("12345")结果为"1,2,3,4,5”#主要用于字符串分隔等