字符串是以单引号或者双引号包括的任意文本,字符串不可变。

创建字符串

格式:str1 = ‘name1’

代码如下:

str1 = '字符串1'
str2 = "字符\r\n串2"

print(str1)
print(str2)

结果:

字符串1
字符
串2

字符串运算

字符串连接

通过符号+来对字符串进行连接操作。

代码如下:

str3 = "my name is "
str4 = "zhangsan"
str5 = str3 + str4
print(str5) # my name is zhangsan

输出重复字符串

代码如下:

str6 = "good"
print(str6 * 3)  # goodgoodgood

访问字符串字符

通过索引下标查找字符串中的字符,索引从0开始

格式:字符串[下标]

代码如下:

str7 = "my name is zhangsan"
print(str7[1])  # y
print(str7[-1]) # n

截取字符串

通过索引下标来截取字符串。

代码如下:

str8 = "my name is li si"
# 从给定起始下标开始截取到给定结束下标之前
str9 = str8[3:6]
# 从头截取到给定下标之前
str10 = str8[:10]
# 从给定下标开始截取到最后
str11 = str8[6:]

print(str9)  # nam
print(str10) # my name is
print(str11) # e is li si

判断字符串是否包含

通过关键词in来判断字符串是否包含字符。

代码如下:

str12 = "my name is li si"
print("my" in str12)  # True
print("my1" in str12) # False

方法

Len()

返回字符串的长度(中英文一致,空格也视为一个字符)。

代码如下:

str13 = "十年饮冰 难凉热血"
str13_2 = "snyb nlrx"

print(len(str13))   # 9
print(len(str13_2)) # 9

Lower()

转换字符串中大写字母为小写字母。

Upper()

转换字符串中小写字母为大写字母。

代码如下:

str20 = 'Let go of that girl'
print(str20.lower()) # let go of that girl
print(str20.upper()) # LET GO OF THAT GIRL

Swapcase()

转换字符串中小写字母为大写字母,大写字母为小写字母。

代码如下:

str21 = 'Every minute counts'

print(str21.swapcase()) # eVERY MINUTE COUNTS

Capitalize()

首字母大写,其他小写。

代码如下:

str22 = 'pRActice Makes Perfect'
print(str22.capitalize()) # Practice makes perfect

Title()

每个单词的首字母大写。

代码如下:

str23 = 'this is title'
print(str23.title()) # This Is Title

Count()

计算特定字符数量,区别大小写。

代码如下:

str24 = 'fear always springs from ignorance'
# 计算f字符总数量
print(str24.count('f'))         # 2
# 计算f字符 从下标3开始 到最后
print(str24.count('f', 3))      # 1
# 计算f字符 从下标3开始 到下标10
print(str24.count('f', 3, 10))  # 0

Find()

从左到右检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾。

得到的第一次出现的下标,没有找到时返回-1。

Rfind()

从左往右检测str字符串是否包含在字符串中,返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

代码如下:

str25 = 'first come, first served'

print(str25.find('first'))                   # 0
print(str25.find('First1'))                  # -1
print(str25.find('first', 10, len(str25)))   # 12
print('-'*10)                                # ----------
print(str25.rfind('first'))                  # 12
print(str25.rfind('First1'))                 # -1
print(str25.rfind('first', 10, len(str25)))  # 12

Index()

从左到右检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾。

返回第一次出现的下标,没有返回-1。

Rindex()

从左到右检测str字符串是否包含在字符串中,返回最后一次出现的下标,没有也是返回-1。

代码如下:

str26 = "if you make yourself an ass, don't complain if people ride you."

print(str26.index('you'))  # 3
print(str26.index('if'))   # 0
print('-'*10)              # ----------
print(str26.rindex('you')) # 59
print(str26.rindex('if'))  # 44

Lstrip()

移除字符串左侧指定的字符,默认为空格。

Rstrip()

移除字符串右侧指定的字符,默认为空格。

Strip()

移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

代码如下:

str27 = '    There is plenty of fish in the sea.'
print(str27.lstrip())  # There is plenty of fish in the sea.

str28 = 'There is plenty of fish in the sea.    '
print(str28.rstrip())  # There is plenty of fish in the sea.

str29 = '    There is plenty of fish in the sea.    '
print(str29.strip())   # There is plenty of fish in the sea.

Ord()

主要用于将字符转换为整数,即获取ASCII给定字符的值;

返回的结果是对应字符的ASCII码。

Chr()

函数是ord()函数的配对函数,主要用一个范围内的整数作参数,返回的结果是对应的字符,可以用十进制或者十六进制。

代码如下:

str30 = 'a'
print(ord(str30)) # 97

str31 = chr(97)   
print(str31)      # a

Split()

字符串转为列表。以str为分隔符截取字符串;num默认字符串长度;

如果设置则仅截取num个字符串,如果多余则不再截取。

代码如下:

str32 = 'Art is long, but life is short.'
print(str32.split(' '))    # ['Art', 'is', 'long,', 'but', 'life', 'is', 'short.']
print(str32.split(' ', 3)) # ['Art', 'is', 'long,', 'but life is short.']

Splitlines()

行分隔,按照(‘\r’,’\r\n’,’\n’)分隔返回

代码如下:

str33 = '''健康的身体贵于黄金铸成的皇冠
远亲不如近邻
勇气和坚定是美德的精神和灵魂
'''
print(str33.splitlines())

结果:

['健康的身体贵于黄金铸成的皇冠', '远亲不如近邻', '勇气和坚定是美德的精神和灵魂']

Join()

列表转字符串。Join(seq)以指定的字符串分隔符,将seq中的所有元素组装成一个字符串。

代码如下:

str34 = ['Walls', 'have', 'ears']
print(' '.join(str34))  # Walls have ears

Max()

最大值

Min()

最小值

代码如下:

print(max('123456')) # 6
print(min('123456')) # 1
print(max('zhangsan')) # z
print(min('zhangsan')) # a

Replace()

Replace(oldstr, newstr, count),用newstr替换oldstr,默认是全部替换。

如果指定了count,那么只替换前count个。

代码如下:

str34 = 'Life is short and art is long'
str35 = str34.replace('is', 'not is', 1)
str36 = str34.replace('is', 'not is')
print(str34) # Life is short and art is long
print(str35) # Life not is short and art is long
print(str36) # Life not is short and art not is long

映射表方式替换

# 创建一个字符串映射表
# 要替换的字符串 目标字符串

t1 = str.maketrans('ax', '12')
# a--1 x--2

str37 = 'hao hao xue xi tian tian xiang shang'
str38 = str37.translate(t1)
print(str38) # h1o h1o 2ue 2i ti1n ti1n 2i1ng sh1ng

Startswitch()

在给定范围内判断是否是以给定的字符串开头,如果没有指定范围,默认整个字符串。

Endswitch()

在给定范围内判断是否是以给定的字符串结尾,如果没有指定范围,默认整个字符串。

代码如下:

str39 = 'my name is zhangsan'
print(str39.startswith('my'))     # True
print(str39.endswith('zhangsan')) # True

Encode()

encode(encoding=’utf-8’, error=’strict’)

对字符串进行编码utf-8/gbk。

代码如下:

str40 = 'first come, first served'
data1 = str40.encode('utf-8')
print(data1)    # b'first come, first served'

Decode()

对字符串进行解码。注意:要与编码时的编码格式一致。

代码如下:

print(data1.decode('utf-8')) 

# first come, first served
忽略错误

当解码时编码不一致时,可以通过ignore参数设置来忽略解码时错误。

代码如下:

str40 = 'first come, first served开心'
data1 = str40.encode('utf-8', 'ignore')

print(data1) 
# b'first come, first served\xe5\xbc\x80\xe5\xbf\x83'

print(data1.decode('gbk', 'ignore')) 
# first come, first served寮蹇

Isalpha()

如果字符串中至少有一个字符且所有的字符都是字母返回True,否则返回False。

代码如下:

str41 = 'zhang san is a lawyer'
print(str41.isalpha())
# 因为有空格 所有返回False

Isalnum()

如果字符串中至少有一个字符且所有的字符是字母或数字返回True,否则返回False。

代码如下:

str42 = '123456'
print(str42.isalnum()) # True

Isupper()

如果字符串中至少有一个英文字符且所有的字符都是大写字母返回True,否则返回False。

代码如下:

print('ABC'.isupper())  # True
print('ABC1'.isupper()) # True
print('ABC#'.isupper()) # True

Islower()

如果字符串中至少有一个英文字符且所有的字符都是小写字母返回True,否则返回False。

代码如下:

print('abc'.islower())  # True
print('abcA'.islower()) # False
print('1'.islower())    # False
print('abc1'.islower()) # True
print('abc#'.islower()) # True

Istitle()

如果字符串是标题化的返回True,否则返回False。

代码如下:

print('Zhang San'.istitle()) # True
print('Zhang san'.istitle()) # False
print('zhang san'.istitle()) # False

Isdigit()

如果字符串中只包含数字字符返回True,否则返回False。

代码如下:

print('123'.isdigit())  # True
print('123a'.isdigit()) # False

Isnumeric()

同isdigit()

代码如下:

print('123'.isnumeric())  # True
print('123a'.isnumeric()) # False

Isdecimal()

字符串中只包含十进制字符。

代码如下:

print('123'.isdecimal()) # True
print('123B'.isdecimal()) # False

Isspace()

如果字符串中只包含空格则返回True,否则返回False。

代码如下:

print(' '.isspace())   # True
print('   '.isspace()) # True
print('\t'.isspace())  # True
print('\n'.isspace())  # True
print('\r'.isspace())  # True
print('not'.isspace()) # False

总结

python 字符串内容和方法总结。