博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字符串操作
阅读量:4572 次
发布时间:2019-06-08

本文共 6351 字,大约阅读时间需要 21 分钟。

1 切片操作

>>> str="hello world!">>> str[1:3]'el'>>> str[:3]'hel'>>> str[2:]'llo world!'
View Code

2 不能直接改变字符串的值,更新字符串可以利用切片

>>> str="hello world!">>> str1=str[:1]+'python'+str[1:]>>> str1'hpythonello world!'
View Code

3 capitalize(): 将字符串第一个字符大写

>>> str='hello world!'>>> str.capitalize()'Hello world!'
View Code

4 casefold(): 将整个字符串小写

>>> str1="Hello world!">>> str1.casefold ()'hello world!'
View Code

5 center(width) 将整个字符串居中(如果不够width则用空格补充)

>>> str="Hello world!">>> str.center(20)'    Hello world!
View Code

6 count(sub[,start[,end]]) sub从start到end出现的次数(默认是整个字符串),不包括end项

>>> str="Hello world!">>> str.center(20)'    Hello world!    '>>> str="Hello world!">>> str.count('l',3)2>>> str.count('l')3>>> str.count('l',3,6)1>>> str.count('l',1,3)1>>> str.count('l',1,4)2
View Code

7 endswith(sub)判断是否是以哪个字符串结尾

>>> str="Hello world!">>> str.endswith('orld!')True>>> str.endswith('orld')False
View Code

8 expandstabs() 将字符串中的'\t'转换为空格

>>> str2="Hello\tworld!">>> str2.expandtabs()'Hello   world!'>>> str2="Hello\tworld!">>> str2.expandtabs()'Hello   world!'>>> str2="Hello\t world!">>> str2.expandtabs()'Hello    world!'>>> str2="Hello\t  world!">>> str2.expandtabs()'Hello     world!'>>> str2="Hello\t   world!">>> str2.expandtabs() 'Hello      world!'>>> str2="Hello\t       world!">>> str2.expandtabs() 'Hello          world!'
View Code

9 find(sub[,start][,end]) 查找字符串中子串从start到end出现的位置并返回下标

>>> str="Hello world!">>> str.find('llo')2>>> str.find('llo',3,8)-1>>> str.find('llo',2,8)2
View Code

10 isalnum(): 判断是否是数字或字母

>>> str="Hello world">>> str.isalnum()False>>> str="Helloworld">>> str.isalnum()True>>> str="Helloworld!">>> str.isalnum()False>>> str="Hello2f23world">>> str.isalnum()True
View Code

11 isspace(): 判断是否为空格

>>> str="hello world">>> str.isspace()False>>> str="">>> str.isspace()False>>> str=" ">>> str.isspace()True>>> str="       ">>> str.isspace()True
View Code

12 isdigit() 判断是否为数字

>>> str="1235 6">>> str.isdigit()False>>> str="12356">>> str.isdigit()True>>> str="12356!">>> str.isdigit()False
View Code

13 isalpha(): 判断是否为字母

>>> str="1fjafajfa">>> str.isalpha()False>>> str="fjafajfa">>> str.isalpha()True>>> str="fjafaj fa">>> str.isalpha()False
View Code

14 islower() 判断是否都为小写

>>> str="afjajga">>> str.islower()True>>> str="afjajgJa">>> str.islower()False
View Code

15 isupper() 判断是否都为大写

>>> str="AFJAJGAJF">>> str.isupper()True>>> str="AFJAJGAJfjF">>> str.isupper()False
View Code

16 istitle(): 判断是否是标题形式字符串(即是连续字符串只有第一个字母大写,其他都是小写,若是有空格,则每个分隔的字符串都满足此)

>>> str="Name Age Address">>> str.istitle()True>>> str="Name Age AdAdress">>> str.istitle()False>>> str="Name Age address">>> str.istitle()False
View Code

17 join(sub)

>>> str="abc">>> str.join('1234')'1abc2abc3abc4'>>> str="-">>> str.join("abc")'a-b-c'
View Code

18 lstrip(): 去掉字符串左边所有的空格

>>> str=" hello world! ">>> str.lstrip()'hello world! '
View Code

19 rstrip(): 去掉字符串右边所有的空格

>>> str=" hello world!  ">>> str.rstrip()' hello world!'
View Code

20 strip(): 去掉字符串左右两边所有空格

>>> str=" hello world!  ">>> str.strip()'hello world!'
View Code

21 replace(old,[,new][,count]); 将字符串中的old子串替换为new,替换count次

>>> str="this is string exampel....wow!!! this is really string">>> str.replace("is","was")'thwas was string exampel....wow!!! thwas was really string'>>> str.replace("is","was",3)'thwas was string exampel....wow!!! thwas is really string'
View Code

22 rfind(sub[,start][,end]) : 从右边开始查找字符串中子串从start到end出现的位置并返回下标(注意start和end是从左往右的,返回的也是从左往右的位置,异常返回-1)

>>> s1="this is really a string example....wow!!!">>> s2="is">>> s1.rfind(s2)5>>> s1.rfind(s2,0,10)5>>> s1.rfind(s2,10,0)-1>>> s1.rfind(s2)5>>> s1.find(s2)2>>> s1.find(s2,0,10)2>>> s1.find(s2,10,0)-1
View Code

23 swapcase():将字符串的大小写反转

>>> str="Hello World!">>> str.swapcase()'hELLO wORLD!'>>>
View Code

24 split(seq):通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串,返回分割后的字符串列表。

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd">>> str.split()['Line1-abcdef', 'Line2-abc', 'Line4-abcd']>>> str.split(' ',1)['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
View Code

25 startwith(sub[,start][,end]):判断从start到end是否以sub开头

>>> str="hello world">>> str.startswith("he")True>>> str.startswith("h")True>>> str.startswith(" h")False
View Code

26 title() 将字符串标题化(即是连续字符串的第一个字母大写,其他都是小写空格,分隔的字符串都遵循此规则)

>>> str="name age address">>> str.title()'Name Age Address'
View Code

27 tanslate(table)  Python translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。

intab="aeiou"outtab="12345"deltab="thw"trantab1=str.maketrans(intab,outtab) #创建字符映射转换表trantab2=str.maketrans(intab,outtab,deltab) #创建字符映射转换表,并删除指定字符test="this is string example....wow!!!"print(test.translate(trantab1))--------结果---------th3s 3s str3ng 2x1mpl2....w4w!!!3s 3s sr3ng 2x1mpl2....4!!!
View Code

28  upper():将字符串转换成大写

>>> str="Hello World!">>> str.upper()'HELLO WORLD!'
View Code

29 lower():将字符串转换成小写

>>> str="Hello World!">>> str.lower()'hello world!'
View Code

30 zfill(width):返回指定长度的字符串,原字符串右对齐,前面填充0。

>>> str="hello world!">>> str.zfill(20)'00000000hello world!'
View Code

31 format() 通过 {} 和 : 来代替以前的 %,增强了字符串的格式化功能

#通过位置print("{0},{1}".format('chuhao',20))print("{},{}".format('chuhao',20))print("{1},{0},{1}".format('chuhao',20))#通过关键字参数print("{name},{age}".format(age=18,name="chuhaho"))class Person:    def __init__(self,name,age):        self.name=name        self.age=age    def __str__(self):        return  "This guy is {self.name},is {self.age} old".format(self=self)print(Person("chuhao",18)) #返回type类型是类print(str(Person("chuhao",18))) #返回type类型是字符串#通过映射lista_list=['chuhao',20,'china']print("my name is {0[0]},from {0[2]},age is {0[1]}".format(a_list))#通过映射dictb_dict={
'name':'chuhao','age':20,'province':'jiangxi'}print("my name is {name},age is {age},from {province}".format(**b_dict))#填充与对齐print("{:>8}".format("189"))print("{:0>8}".format("189"))print("{:a>8}".format("189"))#精度与类型(保留2位小数)print("{:.2f}".format(321.33345))#用来作为金额的千位分隔符print("{:,}".format(1234567890))#其他类型print("{:b}".format(18))print("{:d}".format(18))print("{:o}".format(18))print("{:x}".format(18))--------结果--------chuhao,20chuhao,2020,chuhao,20chuhaho,18This guy is chuhao,is 18 oldThis guy is chuhao,is 18 oldmy name is chuhao,from china,age is 20my name is chuhao,age is 20,from jiangxi 18900000189aaaaa189321.331,234,567,89010010182212
View Code

32 格式化

>>> "%d+%d=%d" %(4,5,4+5)'4+5=9'>>> "%c" %97'a'
View Code

 

转载于:https://www.cnblogs.com/navy2013/p/9729471.html

你可能感兴趣的文章
装饰者模式——Java设计模式
查看>>
HTTP状态码
查看>>
39.递推练习: 菲波那契数列(2)
查看>>
47..贪心 失恋28天-追女孩篇
查看>>
排序精讲
查看>>
【bzoj3172】 Tjoi2013—单词
查看>>
【uoj2】 NOI2014—起床困难综合症
查看>>
js return的用法
查看>>
for_each使用方法详解[转]
查看>>
Apache Storm 与 Spark:对实时处理数据,如何选择【翻译】
查看>>
c :set标签的陷阱(未解决)
查看>>
线性筛素数(欧拉筛)
查看>>
java 序列化与反序列化
查看>>
nginx安装环境
查看>>
罗马数字表示方法
查看>>
ios tableview 上加 textfiled
查看>>
web(获取路径的方法)
查看>>
matlab 数组创建及寻访
查看>>
textmate常用快捷键备忘
查看>>
hibernate中java类的成员变量类型如何映射到SQL中的数据类型变化
查看>>