Python基础数据类型之字符串
-
字符串(str)
-
字符串是 Python 中最常用的数据类型。使用引号('或")来创建字符串。字符串从左至右有顺序,可进行索引、切片,索引、切片后的数据开辟新的内存空间,数据类型仍是字符串。
s = "Python字符串"
-
字符串的类型有两种:一种是
str
,另一种是bytes
-
-
字符串的索引
-
Python 对字符串中的元素取值时,可以使用方括号来截取字符串中的元素
s = "Python字符串" print(s[4]) # 输出结果:o
-
-
字符串的切片
切片的特点是:顾头不顾尾
-
字符串从头切片
s = "Python字符串" print(s[0:6] # 可以简写成:print(s[:6]) # 输出结果:Python
-
字符串从中间切片
s = "Python字符串" print(s[6:8]) # 输出结果: 字符
-
字符串从未尾切片
s = "Python字符串" print(s[-3:]) # 输出结果: 字符串
-
字符串切片加步长
s = "Python字符串" print(s[1:8:2]) # 输出结果: yhn符
-
字符串反向切片
s = "Python字符串" print(s[-1::-1]) # s[-1::-1]表示从字符串的末尾到开头,最后的-1表示反向步长,进行反向切片 # 输出结果:串符字nohtyP
-
-
字符串常用的内置方法
-
upper:将字符串中的英文全部变为大写(★)
s = "Python字符串" s_upper = s.upper() # 不会更改字符串s的值,s_upper会开辟新的内存空间存储数据 print(s_upper) # 输出结果:PYTHON字符串 # 应用场景(用于验证码或其他不区分大小写的验证) code = "QwEr" while 1: user_input_code = input("请输入验证码:").strip() if user_input_code.upper() == code.upper(): print("验证成功!") break else: print("验证失败!请重新输入!")
-
lower:将字符串中的英文全部变为小写(★)
s = "Python字符串" s_lower = s.lower() print(s_lower) # 输出结果:python字符串
-
capitalize:将字符串首字母大写,其他变成小写
s = "pyThon" print(s.capitalize()) #输出结果:Python
-
swapcase:将字符串中的大小写字母互换
s = "pyThon" print(s.swapcase()) #输出结果:PYtHON
-
title:非字母元素隔开的每个单词首字母大写
s = "beautiful is better than ugly." print(s.title()) #输出结果:Beautiful Is Better Than Ugly.
-
center:字符串居中,可设置左右宽度及空白填充字符
s = "Welcome" print(s.center(20,"-")) #输出结果:------Welcome-------
-
find:通过字符查找所在字符串中的索引位置(特点:如果有重复,则找到第一个,后面的就不找了,如果找不到返回值:-1)
s = "Welcome" print(s.find("c")) #输出结果:3 # 如果找不到就返回-1 s = "Welcome" print(s.find("a")) #输出结果:-1
-
index:通过字符查找所在字符串中的索引位置(特点:如果有重复,则找到第一个,后面的就不找了,如果找不到会报错)
s = "Welcome" print(s.index("c")) #输出结果:3 # 如果找不到会报错 s = "Welcome" print(s.index("a")) #输出结果: ''' Traceback (most recent call last): File "C:/Python/Python3.8/test.py", line 5, in <module> print(s.index("a")) ValueError: substring not found '''
-
startswith:判断字符串是否以……开始(★)
s = "Python字符串" print(s.startswith("Py")) # 输出结果:True s = "Python字符串" # print(s.startswith("py")) # # 输出结果:False s = "Python字符串" print(s.startswith("t", 2, 6)) # 判断字符串2到6的切片是否以"t"开头 # 输出结果:True
-
endswith:判断字符串是否以……结束(★)
s = "Python字符串" print(s.endswith("字符串")) # 输出结果:True # 其他功能同startswith
-
replace:替换字符串中指定的元素(★)
s = "Python字符串是Python中最常用的数据类型" print(s.replace("Python", "py")) # 默认将所有指定内容全部替换 # s.replace("Python", "py")不会更改字符串s的值,会开辟新的内存空间存储数据。 # 输出结果:py字符串是py中最常用的数据类型 s = "Python字符串是Python中最常用的数据类型" print(s.replace("Python", "py", 1)) # 1表示从左往右指定替换的个数 # py字符串是Python中最常用的数据类型
-
strip:去除字符串左右两边的空白(★)
s = " \n Python字符串 \t " print(s.strip()) # 输出结果:Python字符串 # 不仅可以去除空白,还可以去除指定的字符 s = "aacdPython字符串abc" print(s.strip("abcd")) # 输出结果:Python字符串 # 去除机制和原理:左右两边同时查找有没有指定去除的元素,有就去除,知道没有后停止。
-
split:将字符串分割成列表(非常重要)(★)
# 默认按照空格分割成列表 s = "Python 字符串" print(s.split()) # 输出结果:['Python', '字符串'] # 按照指定字符分割成列表 s = ",Python,字,符,串" print(s.split(",")) # 输出结果:['', 'Python', '字', '符', '串'] # 按照指定字符的个数分割成列表 s = ",Python,字,符,串" print(s.split(",", 2)) # 输出结果:['', 'Python', '字,符,串']
-
john:将任何可迭代对象换成字符串类型(非常重要)(★)
s = "Python字符串" s1 = "-".join(s) print(s1) # 输出结果:P-y-t-h-o-n-字-符-串 l = ["Python", "列表", "转换", "字符串"] s = "".join(l) print(s) # 输出结果:Python列表转换字符串 l = ["Python", "列表", "转换", "字符串"] s = "-".join(l) print(s) # 输出结果:Python-列表-转换-字符串
-
count:计算字符串中某个字符出现的次数(★)
s = "qwertyasdfgswdfgdef" print(s.count("f")) # 输出结果:3
-
format:字符串格式化输出(★)
# 按照顺序进行格式化输出 s = "{}字符串{}".format("Python", "格式化输出") print(s) # 输出结果:Python字符串格式化输出 # 按照索引进行格式化输出 s = "{1}字符串{0}".format("Python", "格式化输出") print(s) # 输出结果:格式化输出字符串Python # 按照key、value格式化输出 s = "{a}字符串{b}".format(a="Python", b="格式化输出") print(s) # 输出结果:Python字符串格式化输出
-
is系列:对字符串进行判断的一系列内置功能(★)
s = "Python字符串" print(s.isalpha() # 判断是否由字母组成 # 输出结果:True s = "Python字符串" print(s.isdecimal()) # 判断是否由十进制数字组成 # 输出结果:False # 应用案例: while 1: s = input("请输入交易金额:") if s.isdecimal(): s = int(s) print("交易金额为:{}元".format(s)) break else: print("输入有误,请重新输入!") s = "Python字符串" print(s.isalnum()) # 判断是否由字母或数字组成 # 输出结果:False
-
-
字符串的成员运算
所有可迭代对象(字符串、列表、元组等)都支持成员运算,返回布尔值。一般与for循环联用。
-
运算符:in
-
如果在指定的序列中找到值返回 True,否则返回 False。
s = "Python字符串" print("hon" in s) # 输出结果:True s = "Python字符串" print("Pon" in s) # 输出结果:False
-
-
运算符:not in
-
如果在指定的序列中没有找到值返回 True,否则返回 False。
s = "Python字符串" print("字符串" not in s) # 输出结果:False s = "Python字符串" print("字串" not in s) # 输出结果:True
-
-
-
字符串的格式化操作
-
方式一:%-formatting(Python诞生时就有)
s = '%s的格式化%s' %('字符串', '输出') print(s) # 字符串的格式化输出
-
方式二:str.format()(Python 2.6中引入)
s = '{}的格式化{}'.format('字符串', '输出') print(s) # 字符串的格式化输出 s = '{b}的格式化{a}'.format(a='字符串', b='输出') print(s) # 输出的格式化字符串
-
方式三:F-Strings(Python 3.6中引入,不仅格式更简单,支持表达式,而且替换的效率更高)
# 标准格式化输出 s1 = 'Python' s2 = '输出' s = F'{s1}的格式化{s2}' print(s) # Python的格式化输出 # 任意表达式输出 d = {'name':'Python', 'age':2020-1989} s = F'{d["name"]}今年{d["age"]}岁了' print(s) # Python今年31岁了 # 调取函数 def func(): return 'Python' s = F'{func()}的格式化输出' print(s) # Python的格式化输出 # -------------------------分隔符---------------------------- def func(a,b): c = a + b return c s = F'两个数的求和结果是:{func(10,20)}' print(s) # 两个数的求和结果是:30
-
网友评论