Python字符串操作
Python字符串操作
Python字符串处理方法
| 方法及使用 | 说明 |
|---|---|
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中出现的次数"an apple a day".count("a")的结果为4 |
str.replace(old,new) | 返回字符串str副本,所有old字串被替换为new"python".replace("n","n123")结果为"python123" |
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" #主要用于字符串分隔等 |
字符串类型的格式化
格式化是对字符串进行格式表达的方式
字符串格式化使用.format()方法,用法如下:
<模板字符串>.format(<逗号分隔的参数>)