字符串(str)
字符串是字符的不可变序列
字符串的表示方式
-
使用单引号(') 例:a='str'
-
使用双引号("") 例:a=”hello word“
-
使用三引号(""" """) 例:a=""" hello world""",允许多行
>>> a='str' >>> a 'str' >>> a="hello world" >>> a 'hello world' >>> a=""" ... ae ... hello ... """ >>> a '\nae\nhello\n'
级连字符串
如果把两个字符串相邻放着,他们会被python自动级连
a = "hello",'world' print(a) 输出:('hello', 'world')
原样输出引号里面的内容
>>> a=r"hello world\n hunan" #r表示不转义,作为原始字符串输出 >>> print(a) hello world\n hunan
字符串的切片取值
>>> str1 = "abcde" >>> print(str1[3]) d >>> print(str1[-2]) d 通过下标切片 #str[start:end:step]) # step 默认为1,每几步取一个值 #1、如果step为正表示从左到右截取,如果step为负,表示从右到左截取 #2、确认start和end的位置 #3、确认step的步长是多少 str1="abcdefghijk" print(str1[3:]) print(str1[:7]) print(str1[3:5]) print(str1[3:8:2]) print(str1[-7:1:-2]) 输出: defghijk abcdefg de dfh ec
字符串的常用方法
判断系列(ture/false)
str1 = "123450" str2 = "123一二三" str3 = "abc450" str4 = "hello" print(str1.isdigit()) #是不是只包含数字1、① print(str2.isnumeric()) #是不是只包含数字1、一 print(str3.istitle()) #是不是标题,首字母大写就是 print(str4.istitle()) 输出为: True True False False
查找统计类
>>> len("shdsjkf") 7 >>> len("shdsjkf中国") 9 >>> 'dhjfsasdaa'.count("a") 3 >>> 'dhjfsasdaa'.count("aa") 1 >>> 'dhjfsasdaa'.count("aa",7) #从第七位开始查找有几个aa 1 >>> 'hfdjkskja'.index("a") 8 >>> 'hfdjkskja'.index("aa") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> 'hfdjkskja'.find("a") #find 比index好一点,index没有直接报错,find返回-1 8 >>> 'hfdjkskja'.find("aa") -1
转换类
>>> a = "hello" >>> print(a.upper()) HELLO >>> print(a.lower()) hello >>> print(a.title()) Hello World >>> print(a.swapcase()) HELLO >>>msg = "ab**5%ef" >>>print(msg.replace("*","#").replace("%","#")) ab##5#ef