python字符串操作

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类型是字符串

#通过映射list
a_list=['chuhao',20,'china']
print("my name is {0[0]},from {0[2]},age is {0[1]}".format(a_list))

#通过映射dict
b_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,20
chuhao,20
20,chuhao,20
chuhaho,18
This guy is chuhao,is 18 old
This guy is chuhao,is 18 old
my name is chuhao,from china,age is 20
my name is chuhao,age is 20,from jiangxi
     189
00000189
aaaaa189
321.33
1,234,567,890
10010
18
22
12
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值