比较运算
s1 = 'a whole new world' s2 = 'hello world' print(s1 == s2, s1 < s2) # False True print(s2 == 'hello world') # True print(s2 == 'Hello world') # False print(s2 != 'Hello world') # True s3 = '骆昊' print(ord('骆'), ord('昊')) # 39558 26122 s4 = '王大锤' print(ord('王'), ord('大'), ord('锤')) # 29579 22823 38180 print(s3 > s4, s3 <= s4) # True False
is运算符
s1 = 'hello world' s2 = 'hello world' s3 = s2 # 比较字符串的内容 print(s1 == s2, s2 == s3) # True True # 比较字符串的内存地址 print(s1 is s2, s2 is s3) # False True
成员运算 in和not in
s1 = 'hello, world' print('wo' in s1) # True s2 = 'goodbye' print(s2 in s1) # False
获取字符串长度
s1 = 'hello, world' print(len(s1)) # 12 print(len('goodbye, world')) # 14
索引和切片
如果希望从字符串中取出某个字符,我们可以对字符串进行索引运算,运算符是[n],其中n是一个整数,假设字符串的长度为N,那么n可以是从0到N-1的整数,其中0是字符串中第一个字符的索引,而N-1是字符串中最后一个字符的索引,通常称之为正向索引;在Python中,字符串的索引也可以是从-1到-N的整数,其中-1是最后一个字符的索引,而-N则是第一个字符的索引,通常称之为负向索引。注意,因为字符串是不可变类型,所以不能通过索引运算修改字符串中的字符。
s1 = 'abc123456' N = len(s1) # 获取第一个字符 print(s1[0], s1[-N]) # a a # 获取最后一个字符 print(s1[N-1], s1[-1]) # 6 6 # 获取索引为2或-7的字符 print(s1[2], s1[-7]) # c c # 获取索引为5和-4的字符 print(s1[5], s1[-4]) # 3 3 s1 = 'abc123456' # i=2, j=5, k=1的正向切片操作 print(s1[2:5]) # c12 # i=-7, j=-4, k=1的正向切片操作 print(s1[-7:-4]) # c12 # i=2, j=9, k=1的正向切片操作 print(s1[2:]) # c123456 # i=-7, j=9, k=1的正向切片操作 print(s1[-7:]) # c123456 # i=2, j=9, k=2的正向切片操作 print(s1[2::2]) # c246 # i=-7, j=9, k=2的正向切片操作 print(s1[-7::2]) # c246 # i=0, j=9, k=2的正向切片操作 print(s1[::2]) # ac246 # i=1, j=-1, k=2的正向切片操作 print(s1[1:-1:2]) # b135 # i=7, j=1, k=-1的负向切片操作 print(s1[7:1:-1]) # 54321c # i=-2, j=-8, k=-1的负向切片操作 print(s1[-2:-8:-1]) # 54321c # i=7, j=-10, k=-1的负向切片操作 print(s1[7::-1]) # 54321cba # i=-1, j=1, k=-1的负向切片操作 print(s1[:1:-1]) # 654321c # i=0, j=9, k=1的正向切片 print(s1[:]) # abc123456 # i=0, j=9, k=2的正向切片 print(s1[::2]) # ac246 # i=-1, j=-10, k=-1的负向切片 print(s1[::-1]) # 654321cba # i=-1, j=-10, k=-2的负向切片 print(s1[::-2]) # 642ca
循环遍历
如果希望从字符串中取出每个字符,可以使用for循环对字符串进行遍历,有两种方式。
方式一:
s1 = 'hello' for index in range(len(s1)): print(s1[index])
方式二:
s1 = 'hello' for ch in s1: print(ch)
字符串的方法 调用:变量名.方法名()
s1 = 'hello, world!' # 使用capitalize方法获得字符串首字母大写后的字符串 print(s1.capitalize()) # Hello, world! # 使用title方法获得字符串每个单词首字母大写后的字符串 print(s1.title()) # Hello, World! # 使用upper方法获得字符串大写后的字符串 print(s1.upper()) # HELLO, WORLD! s2 = 'GOODBYE' # 使用lower方法获得字符串小写后的字符串 print(s2.lower()) # goodbye
查找操作find,index
如果想在一个字符串中查找有没有另外一个字符串,可以使用字符串的find或index方法。
s1 = 'hello, world!' # find方法从字符串中查找另一个字符串所在的位置 # 找到了返回字符串中另一个字符串首字符的索引 print(s1.find('or')) # 8 # 找不到返回-1 print(s1.find('shit')) # -1 # index方法与find方法类似 # 找到了返回字符串中另一个字符串首字符的索引 print(s1.index('or')) # 8 # 找不到引发异常 print(s1.index('shit')) # ValueError: substring not found
逆向查找 rfind和rindex
s = 'hello good world!' # 从前向后查找字符o出现的位置(相当于第一次出现) print(s.find('o')) # 4 # 从索引为5的位置开始查找字符o出现的位置 print(s.find('o', 5)) # 7 # 从后向前查找字符o出现的位置(相当于最后一次出现) print(s.rfind('o')) # 12
性质判断
可以通过字符串的startswith、endswith来判断字符串是否以某个字符串开头和结尾;还可以用is开头的方法判断字符串的特征,这些方法都返回布尔值
s1 = 'hello, world!' # startwith方法检查字符串是否以指定的字符串开头返回布尔值 print(s1.startswith('He')) # False print(s1.startswith('hel')) # True # endswith方法检查字符串是否以指定的字符串结尾返回布尔值 print(s1.endswith('!')) # True s2 = 'abc123456' # isdigit方法检查字符串是否由数字构成返回布尔值 print(s2.isdigit()) # False # isalpha方法检查字符串是否以字母构成返回布尔值 print(s2.isalpha()) # False # isalnum方法检查字符串是否以数字和字母构成返回布尔值 print(s2.isalnum()) # True
格式化字符串
s1 = 'hello, world' # center方法以宽度20将字符串居中并在两侧填充* print(s1.center(20, '*')) # ****hello, world**** # rjust方法以宽度20将字符串右对齐并在左侧填充空格 print(s1.rjust(20)) # hello, world # ljust方法以宽度20将字符串左对齐并在右侧填充~ print(s1.ljust(20, '~')) # hello, world~~~~~~~~
字符串格式化
用print函数输出字符串时,可以用下面的方式对字符串进行格式化
1.
a = 321 b = 123 print('%d * %d = %d' % (a, b, a * b))
2.
a = 321 b = 123 print('{0} * {1} = {2}'.format(a, b, a * b))
3.
a = 321 b = 123 print(f'{a} * {b} = {a * b}')
strip 修剪操作
帮我们获得将原字符串修剪掉左右两端空格之后的字符串
还有:lstrip()和rstrip();
s1 = ' jackfrued@126.com ' # strip方法获得字符串修剪左右两侧空格之后的字符串 print(s1.strip()) # jackfrued@126.com
练习1:设计一个生成指定长度验证码的函数。
第一种方法:
import random ALL_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def generate_code(code_len=4): code = "" for i in range(code_len): index = random.randrange(0,len(ALL_CHARS)) code+=ALL_CHARS[index] return code print(generate_code(10))
第二种方式:
import random import string ALL_CHARS = string.digits + string.ascii_letters def generate_code(code_len=4): :param code_len: 验证码的长度(默认4个字符) :return: 由大小写英文字母和数字构成的随机验证码字符串 return ''.join(random.choices(ALL_CHARS, k=code_len)) print(generate_code(10))
说明:random模块的sample和choices函数都可以实现随机抽样,
sample实现无放回抽样,这意味着抽样取出的字符是不重复的;
choices实现有放回抽样,这意味着可能会重复选中某些字符。
这两个函数的第一个参数代表抽样的总体,而参数k代表抽样的数量。