天天看点

python字符串字符串详解

字符串详解

字符串是Python中非常重要的数据类型。

字符串创建

>>> result=""

>>> type(result)

<class 'str'>

>>> isinstance(result,str)

True

字符串操作

字符串运算

>>> "a"+"b"+"c"

'abc'

拼接字符+

>>> "hi"*4

'hihihihi'

重复输出*

>>> "abcd"[1]

'b'

索引获取字符串中的字符

>>> "abcd"[1:4]

'bcd'

截取字符串中的一部分

>>> "a" in "abc"

True

>>> "a" not in "bc"

True

in/not in 成员运算符

字符串格式化%

>>> print ("%c" % "c")  

c

>>> print ("%c" % 97)

a

格式化ascii码中的int或char

>>> print ("%d" % 10)  

10

>>> print ("%6d" % 10)   

    10

格式化整数

不够位数的时候补空格

>>> print ("%f" % 10)  

10.000000

>>> print ("%.2f" % 10)  

10.00

>>> print ("%6.2f" % 10) 

10.00

格式化小数

保留两位小数

位数为6,保留两位小数

>>> print ("%o" % 8)  

10

八进制

>>> print ("%x" % 31) 

1f

十六进制

>>> print ("%e" % 10) 

1.000000e+01

科学记数法

>>> print ("%s%s" % ("a","b"))

ab

>>> print ("%s%s" % (1,2))

12

>>> print ("%s%s" % (1,2.3))

12.3

格式化字符串,常用

字符串测试

startswith():开头

>>> "abcd".startswith("a")    

True

>>> "abcd".startswith("A")

False

endswith():结尾

>>> "abcd".endswith("D")

False

>>> "abcd".endswith("d")

True

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

>>> "12".isalpha()

False

>>> "ab".isalpha()  

True

isalnum():判断是否为字母或数字组成

>>> "ab".isalnum()  

True

>>> "a1".isalnum()

True

isdigit():判断是否为纯数字

>>> "123".isdigit()  

True

>>> "12a".isdigit()

False

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

>>> " ".isspace()    

True

>>> " \n\r".isspace()

True

>>> "\r".isspace()

True

>>> " n\r".isspace()

False

islower():判断是否字母都是小写

>>> "abc".islower()

True

>>> "Abc".islower()

False

isupper():判断是否字母都是大写

>>> "ABC".isupper()

True

>>> "ABc".isupper()

False

istitle():判断单词的首字母都是大写,其余都是小写

>>> "AAB".istitle()

False

>>> "Aab".istitle()

True

>>> "Aab Tr".istitle()

True

>>> "Aab TR".istitle()

False

>>> "Aab tr".istitle()

False

字符串大小写互换

upper():将字母转换为大写

>>> "abc".upper()

'ABC'

lower():将字母转换为小写

>>> "ABC".lower()

'abc'

swapcase():将字母大小写互换

>>> "AAbbCCdd".swapcase()

'aaBBccDD'

title():将每个单词的首字母大写

>>> "an apple".title() 

'An Apple'

#与前者等价

>>> import string       

>>> string.capwords("an apple")

'An Apple'

capitalize():将句子中的第一个单词首字母大写

>>> "an apple".capitalize()

'An apple'

字符串搜索

find():可指定范围查找,默认为从0到字符串的长度;如果存在目标字符串则返回其所在的第一个索引位置,不存在则返回-1

>>> new_str="abcdefabcdef"

>>> new_str.find("cd")       #默认范围

2

>>> new_str.find("t")

-1

>>> new_str.find("cd",5,10)    #指定范围

8

rfind():从右向左查找目标字符串,存在则返回其所在的第一个索引位置,不存在则返回-1

>>> new_str="abcdefabcdef"

>>> new_str.rfind("cd")

8

>>> new_str.rfind("cd",10,0)

-1

>>> new_str.rfind("t")

-1

re.findall():返回存在的所有目标字符串列表,不存在则返回空列表

>>> import re

>>> re.findall("a","abcdea")

['a', 'a']

>>> re.findall("a","abaaa")

['a', 'a', 'a', 'a']

>>> re.findall("d","abc")

[]

index():同find方法,只不过找不到目标字符串时会报异常

>>> new_str="abcdefabcdef"

>>> new_str.index("c")

2

>>> new_str.index("c",5,10)

8

>>> new_str.index("t")

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

rindex():同find方法,只不过找不到目标字符串时会报异常

>>> new_str="abcdefabcdef"

>>> new_str.rindex("c")

8

>>> new_str.rindex("t")

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

字符串拼接

join():将序列中的元素以指定的字符连接生成一个新的字符串

>>> new_list=['a', 'b', 'c', 'd']

>>> "".join(new_list)

'abcd'

>>> " ".join(new_list)

'a b c d'

>>> "+".join(new_list)

'a+b+c+d'

>>> new_str=("adf","sdf")

>>> "".join(new_str)

'adfsdf'

字符串分割

split():通过指定分割符将字符串进行切片,默认分割符为空格;可指定分割次数;返回的是一个列表类型

>>> new_str="a*b*c*d"

>>> new_str.split("*",2)     #分割2次

['a', 'b', 'c*d']

>>> new_str="a b c d"

>>> new_str.split()

['a', 'b', 'c', 'd']

splitlines():按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,默认参数为False,即不包含换行符,如果为 True,则保留换行符

>>> new_str="abc\r\n \nef\r"

>>> new_str.splitlines()

['abc', ' ', 'ef']

>>> new_str.splitlines(True)

['abc\r\n', ' \n', 'ef\r']

字符串替换

replace():把字符串中的旧字符串换成新的;如果指定第三个参数max,则替换不超过max次

>>> new_str="**my name is gang!"

>>> new_str=new_str.replace("*","")

>>> new_str

'my name is gang!'

>>> new_str=new_str.replace("!","")

>>> new_str

'my name is gang'

>>> "***yu***".replace("*","",4)

'yu**'

字符串对齐

ljust():返回一个原字符串左对齐(使用默认空格填充至指定长度的新字符串,也可指定填充内容。如果指定的长度小于原字符串的长度则返回原字符串)

>>> "abc".ljust(10,"*") 

'abc*******'

>>> "abcdef".ljust(5)

'abcdef'

rjust():返回一个原字符串右对齐(同上)

>>> "abc".rjust(10,"*")

'*******abc'

center():返回一个原字符串居中(同上)

>>> "abc".center(10,"*")

'***abc****'

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

>>> "abc".zfill(8)

'00000abc

字符串删除字符

strip():用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列(*不能将字符串内部的空格或换行符去掉)

>>> "  \nabc \r".strip()

'abc'

>>> "  \nab \nc \r".strip()

'ab \nc'

>>> "0000gang000".strip("0")

'gang'

lstrip():删除字符串左边的空格或指定字符

>>> "  \nabc \r".lstrip()

'abc \r'

>>> "000what?".lstrip("0")

'what?'

rstrip():删除字符串末尾的指定字符(默认为空格).

>>> "  \nabc \r".rstrip()

'  \nabc'

>>> "I am a boy!666".rstrip("6")

'I am a boy!'

字符串编码、解码

>>> "yuzhigang".encode("base64")                    # base64编码

'eXV6aGlnYW5n\n'

>>> "yuzhigang".encode("base64").decode("base64")     # base64解码

'yuzhigang'

字符串映射

str.maketrans(intab,outtab): 创建字符映射的转换表;intab参数表示需要转换的字符串;outtab表示转换的目标字符;intab与outtab长度必须相同,且一一对应

translate():将映射关系表现出来

>>> m=str.maketrans("123","abc")

>>> s="54321123789"

>>> s.translate(m)

'54cbaabc789'