字符串
1.什么是字符串
- 用引号引起来的一串字符
单引号和双引号使用时需要注意匹配关系,且不可以换行
如果要换行,使用三单引号或三双引号
2.字符串的运算及常见操作
(1)拼接
a='Hello'
b=',Python'
print(a+b)
#输出结果:
Hello,Python
拼接基于同一种类型
(2)重复
a='Hello'
print(a*3)
#输出结果:
HelloHelloHello
(3)索引,切片([:],[::])
#正着索引:
sr="python"
for i in range(len(sr)):
print(sr[i],end=' ')
#反过来索引:
for i in range(len(sr)):
print(sr[-i-1],end=' ')
#输出结果:
p y t h o n
n o h t y p
#切片:
sr="Life is short,you need python."
print(len(sr))
print(sr[:5]) #sr[5]不包括
print(sr[0:4:2]) #2表示步长
print(sr[0::2])
#输出结果:
30
Life
Lf
Lf ssotyune yhn
(4)大小写转换
- sr.lower():转小写
- sr.upper():转大写
- sr.swapcase():大小写互换
- sr.title():按照标题格式输出
- sr.capitalize():首字母大写
#验证码确认(不区分大小写)
a="pyThOn"
b=str(input("输入验证码:"))
if b.lower()==a.lower():
print("Right!")
else:
print("Sorry.")
#输出结果:
输入验证码:python
Right!
输入验证码:rython
Sorry.
#两次密码确认(区分大小写)
c=input("请输入密码:")
d=input("请确认密码:")
if c==d:
print("OK!")
else:
print("Sorry.")
#输出结果:
请输入密码:12nn12
请确认密码:12Nn12
Sorry.
请输入密码:12345n
请确认密码:12345n
OK!
(5)字符串的格式输出对齐
- sr.center([len],[填充符号]):居中对齐
- sr.ljust([len],[填充符号]):居左对齐
- sr.rjust([len],[填充符号]):居右对齐
- sr.zfill([len]):居右对齐,默认填充0
sr="Life is short,you NEED python."
print(sr.center(50,' '))
print(sr.ljust(50,'#'))
print(sr.rjust(50,'#'))
print(sr.zfill(50))
#输出结果:
Life is short,you NEED python.
Life is short,you NEED python.####################
####################Life is short,you NEED python.
00000000000000000000Life is short,you NEED python.
(6)删除指定字符
- sr.strip():删除两边空字符
- sr.lstrip():删除左边空字符
- sr.rstrip():删除右边空字符
sr="##########Life is short,you NEED python.##########"
print(sr.strip("#"))
print(sr.lstrip("#"))
print(sr.rstrip("#"))
#输出结果:
Life is short,you NEED python.
Life is short,you NEED python.##########
##########Life is short,you NEED python.
sr=" Life is short,you NEED python. "
print(sr)
print(sr.strip())
print(sr.lstrip())
print(sr.rstrip())
#输出结果:
Life is short,you NEED python.
Life is short,you NEED python.
Life is short,you NEED python.
Life is short,you NEED python.
(7)计数
- sr.count()
sr="Life is short,you NEED python."
print(sr.count('o',9,17)) #sr[9]到sr[16]内“o”的个数
#输出结果:
2
(8)字符串搜索定位和替换
- sr.find():查找元素并返回第一次出现的元素索引值,查找不到返回-1
- sr.rfind():查找元素并返回第二次出现的元素索引值,查找不到返回-1
- sr.index():查找元素并返回第一次出现的元素索引值,查找不到报错
- sr.rindex():从右到左查找
- sr.replace([现有],[新的]):替换
sr="Life is short,you NEED python."
print(sr.find('s'))
print(sr.find('o',7,12))
print(sr.rfind('s'))
#输出结果:
6
10
8
print(sr.index('o'))
print(sr.rindex('o'))
#输出结果:
10
27
print(sr.replace('s','S'))
print(sr.replace('o','O',2)) #2为限制替换的个数
#输出结果:
Life iS Short,you NEED python.
Life is shOrt,yOu NEED python.
(9)字符串条件判断
- isalnum():判断字符串有字母或数字组成
- isalpha():仅有字母
- isdigit():仅有数字
a="asd123"
print(a.isalnum())
print(a.isalpha())
print(a.isdigit())
#输出结果:
True
False
False
(10)制表符的转化
- sr.expandtabs()
sr="Lif\te is short,you NEED python."
print(sr)
print(sr.expandtabs())
#输出结果:
Lif e is short,you NEED python.
Lif e is short,you NEED python.
(11)字符串的分割变换
- sr.join():将指定字符插入到元素之间
- sr.split():以指定字符分割字符串并去除该字符
- sr.partition():以指定字符分割字符串并保留该字符
a="wzx"
b="cl"
print(b.join(a))
li=["I","Love","Python"]
print("+".join(li))
#输出结果:
wclzclx
I+Love+Python
sr="Life is short,you NEED python."
print(sr.split('o'))
print(sr.split('o',2))
#输出结果:
['Life is sh', 'rt,y', 'u NEED pyth', 'n.']
['Life is sh', 'rt,y', 'u NEED python.']
print(sr.partition('o'))
#输出结果:
('Life is sh', 'o', 'rt,you NEED python.')
(12)ASCII值和字符转化
- chr():ASCII值转化为字符
- ord():字符转化为ASCII值
for i in range (ord('a'),ord('z')+1):
print(chr(i),end=' ')
#输出结果:
a b c d e f g h i j k l m n o p q r s t u v w x y z
#拓展:string模块
demo:
import string
print(dir(string))
print(string.ascii_lowercase) #小写
print(string.ascii_uppercase) #大写
print(string.ascii_letters) #小写和大写结合
#输出结果:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
for i in range(8):
print(oct(i),end=' ')
print( )
for i in range(16):
print(hex(i),end=' ')
#输出结果:
0o0 0o1 0o2 0o3 0o4 0o5 0o6 0o7
0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf
- %d :dec 十进制
- %o :oct 八进制
- %x : hex 十六进制
print('%d'% 17)
print('%o'% 17)
print('%x'% 17)
#输出结果:
17
21
11