用单引号或者双引号创建
-
单引号和双引号使用时注意匹配关系,且不可以换行
-
如果要换行,用三单引号或者三双引号
字符串的运算及常见操作
(1)拼接
a="hello"
b=",python."
print(a+b)
'''
结果:
D:\Python\python.exe D:/python_01/string.py
hello,python.
Process finished with exit code 0
'''
拼接基于同一种数据类型
(2)重复
a="hello "
print(a*3)
'''
结果:
D:\Python\python.exe D:/python_01/string.py
hello hello hello
Process finished with exit code 0
'''
(3)索引(偏移),切片
索引:[ ]
#遍历字符串"Python"
sr="Python"
for i in range(len(sr)):
print(sr[i])
#也可以使用:
for i in "Python":
print(i)
'''
结果均为:
D:\Python\python.exe D:/python_01/string.py
P
y
t
h
o
n
Process finished with exit code 0
'''
切片:[:],[: :]
sr = "life is short,you need python."
print(len(sr)) #得出字符串长度
print(sr[:4])
print(sr[1:4:2])
print(sr[3::4]) # 从第三位开始到最后,取+4(步长)位的数,3,7,11...
print(sr[1::2]) # 从第一位开始到最后,取+2位的数,1,3,5,7...
print(sr[::-1]) # 从第一位至末位,步长为1倒序取数
print(sr[::-2]) # 从第一位至末位,步长为1倒序取数
'''
结果:
D:\Python\python.exe D:/python_01/string.py
30
life
ie
e roepo
iei hr,o edpto.
.nohtyp deen uoy,trohs si efil
.otpde o,rh iei
Process finished with exit code 0
(4)大小写转换
sr="life is short,you NEED python."
print(sr.lower())#转小写
print(sr.upper())#转大写
print(sr.title())#转为标题形式
print(sr.swapcase())#大小写互换
print(sr.capitalize())#转换为首字母大写
'''
D:\Python\python.exe D:/python_01/string.py
life is short,you need python.
LIFE IS SHORT,YOU NEED PYTHON.
Life Is Short,You Need Python.
LIFE IS SHORT,YOU need PYTHON.
Life is short,you need python.
Process finished with exit code 0
'''
简单的验证码匹配:
certid = "YHoS"
i = input("请输入验证码:")
if i.lower() == certid.lower():
print("输入正确")
else:
print("对不起,输入错误,请重试")
'''
(1):错误示范
D:\Python\python.exe D:/python_01/string.py
请输入验证码:qudk
对不起,输入错误,请重试
Process finished with exit code 0
(2):正确示范
D:\Python\python.exe D:/python_01/string.py
请输入验证码:yhos
输入正确
Process finished with exit code 0
'''
(5)字符串的格式输出对齐
#sr.center([len],[填充符号])
sr = "life is short,you need python."
print(sr.center(41, "#")) # 居中对齐
print(sr.ljust(41, "*")) # 居左对齐
print(sr.rjust(41, "$")) # 居右对齐
print(sr.zfill(41)) # 居右对齐,默认填充0
'''
结果:
D:\Python\python.exe D:/python_01/string.py
######life is short,you need python.#####
life is short,you need python.***********
$$$$$$$$$$$life is short,you need python.
00000000000life is short,you need python.
Process finished with exit code 0
'''
(6)删除指定字符
strip,lstrip,rstrip
sr = "######life is short,you need python.#####"
print(sr.strip("#"))
print(sr.lstrip("#"))
print(sr.rstrip("#"))
'''
结果:
D:\Python\python.exe D:/python_01/string.py
life is short,you need python.
life is short,you need python.#####
######life is short,you need python.
Process finished with exit code 0
'''
(7)计数
count
sr = "life is short,you need python."
print(sr.count("o"))
print(sr.count("o", 9, 15)) # 在9到15位范围内计算o的个数
print(sr.count("i",9,17))
'''
结果:
D:\Python\python.exe D:/python_01/string.py
3
1
0
Process finished with exit code 0
'''
(8)字符串搜索定位和替换
查找:find,index
sr = "life is short,you need python."
print(sr.find("e")) # 查找元素并返回第一次出现的元素的索引值
print(sr.find("e", 19, 25)) # 在19到25位范围内查找元素并返回第一次出现的元素的索引值
print(sr.find("c", 1, 16)) # 查不到,返回-1
print(sr.index("e",19,25)) # 在19到25位范围内查找元素并返回第一次出现的元素的索引值
print(sr.index("c",1,16)) #查不到,报错
print(sr.rindex("e",19,25)) #倒序查找
'''
D:\Python\python.exe D:/python_01/string.py
3
19
-1
19
Traceback (most recent call last):
File "D:/python_01/string.py", line 71, in <module>
print(sr.index("c",1,16))
ValueError: substring not found
20
Process finished with exit code 0
'''
替换:
replace
print(sr.replace("t", "T"))
print(sr.replace("t", "T", 1)) #指定替换个数
'''
D:\Python\python.exe D:/python_01/string.py
life is shorT,you need pyThon.
life is shorT,you need python.
Process finished with exit code 0
'''
(9)字符串条件判断
a = "abc666def"
b = "abc"
c = "hgsk78sowjs#%^"
print(b.isalnum()) # 判断字符串有字母或者数字组成
print(c.isalnum())
print(a.isalpha()) # 判断字符串是否仅有字母
print(b.isalpha())
print(a.isdigit()) # 判断字符串是否仅有数字
'''
结果:
D:\Python\python.exe D:/python_01/string.py
True
False
False
True
False
Process finished with exit code 0
'''
(10)制表符的转化
(11)字符串的分割变换
sr = "life is short,you need python."
print("+".join(sr)) # 将指定字符插入到元素之间
print(sr.split("o")) # 以指定字符分割字符串并去除该字符
print(sr.split("o", 2)) # 指定用来分割的"o"的个数(即保留第三个及往后的"o")
print(sr.partition("o")) # 以指定字符分割字符串并保留该字符
'''
结果:
D:\Python\python.exe D:/python_01/string.py
l+i+f+e+ +i+s+ +s+h+o+r+t+,+y+o+u+ +n+e+e+d+ +p+y+t+h+o+n+.
['life is sh', 'rt,y', 'u need pyth', 'n.']
['life is sh', 'rt,y', 'u need python.']
('life is sh', 'o', 'rt,you need python.')
Process finished with exit code 0
'''
(12)ASCII值和字符的转化
# chr() digit-->alpha
# ord() alpha-->digit
for i in range(ord("a"), ord("z") + 1):
print(i, end=' ')
print(chr(i), end=' | ')
'''
结果:
D:\Python\python.exe D:/python_01/zifuchuan.py
97 a | 98 b | 99 c | 100 d | 101 e | 102 f | 103 g | 104 h | 105 i | 106 j | 107 k | 108 l | 109 m | 110 n | 111 o | 112 p | 113 q | 114 r | 115 s | 116 t | 117 u | 118 v | 119 w | 120 x | 121 y | 122 z |
Process finished with exit code 0
'''
拓展:string模块
import string
print(dir(string)) #查看string模块里的所有内容
'''
结果:
D:\Python\python.exe D:/python_01/zifuchuan.py
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
Process finished with exit code 0
'''
print(string.ascii_letters) # ascii字母
print(string.ascii_lowercase) # ascii小写字母
print(string.ascii_uppercase) # assii大写字母
'''
结果:
D:\Python\python.exe D:/python_01/zifuchuan.py
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Process finished with exit code 0
'''