字符串
一、字符串简介
字符串是编程世界中最常用的一个数据类型,它表示一个文本,例如表示一个人的名字”Mr_lee”。
在Python字符串需要使用引号来包围。可以是单引号、双引号或三引号
1 | # 单引号、双引号用来表示单行字符串 s = "Tom\nJack" print(s) |
字符串的特点:
- 具有天生的跨平台的特性(C、C++、Java…)
- 是一个序列(有序的数列)
- 支持下标操作
- 支持切片
- 可迭代对象
- 不可变类型
s = 'abc' s= 'Tom' 并不是修改了内容而是修改了指向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18s = "String"
print(s)
s[3] = 'o' # 不可修改内容 Error
print(s)
s = "Strong"
print(s) # 改变指向
a = 5
print(id(a)) # 1871015072
a = 10
print(id(a)) # 1871015232 # 指向发生了改变
a = [1,2]
print(id(a)) # 41174664
a[0] = 10 # 修改列表的内容-元素 列表的指向并没有发生改变
print(id(a)) # 41174664Python中的字符串与C、C++的不同之处:
Python没有单字符,所有的单字符也是当作字符串进行处理
s = 'a' s = "a" 它们都是字符串 类型都是str
而C、C++中 ‘’表示的为单字符,而“”表示的为字符串
char s = 'A' string s = "ABC" 类型不一样
二、字符串的创建
直接创建
1
2s = 'abc'
print(s) # 大多数情况下使用工厂函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16s1 = str()
print(s1) # -> '' 空字符串 长度为0
s2 = str(' ')
print(s2) # 空格 长度为1
s3 = str(123)
print(s3) # 将int 转为 字符串str
s4 = str(123.4) # -> '123.4' 字符串在使用print输出时,不会显示引号
s5 = str(True) # -> 'True'
s6 = str(None) # -> 'None'
s7 = str([1,2,3]) # -> '[1,2,3]'
# 补充: eval()
# print(eval("1+2")) -> 3 eval("[1,2,3,4]") -> [1,2,3,4]
三、字符串的访问
可以通过下标或切片来获取字符串中的内容
1 | s = 'Hello World' |
四、字符串运算符
1 | 1. + 实现字符串的拼接 |
五、字符串中的方法
大小写转换
s.capitalize()
: 将首字母转为大写1
2
3s = 'helloworld'
print(s.capitalize()) # -> Helloworld 转换后生成新的字符串
print(s) # -> helloworld 原字符串不变s.lower()
: 将字符串转为小写1
print("HelloWorld".lower()) # -> helloworld
s.upper()
:将字符串转为大写1
print("helloworld".upper()) # -> HELLOWORLD
s.swapcase()
:翻转大小写1
print("HelloWorld".swapcase()) # -> hELLOwORLD
s.title()
:标题化字符串,将所有单词的首字母转为大写,其余的小写1
print("hello world".title()) # -> Hello World
s.casefold()
: 全部转为小写 – 类似于lower() 功能比lower更强大1
2print("ΕΖΗ".lower()) # εζη
print("ΕΖΗ".casefold()) # εζη
字符串样式
s.center(width[,fillchar])
返回一个字符串居中,并使用空格来填充至长度为width的新字符串,fillchar为可选参数,表示要填充的内容1
2
3s = "helloworld"
print(s.center(20)) # -> ' helloworld '
print(s.center(20,'*')) # -> '*****helloworld*****'s.ljust(width[,fillchar])
:返回一个字符串左对齐,使用空格填充至长度为width的新字符串1
2
3s = "helloworld"
print(s.ljust(20)) # -> 'helloworld '
print(s.ljust(20,'*')) # -> 'helloworld**********'s.rjust(width[,fillchar])
:返回一个字符串右对齐,使用空格填充至长度为width的新字符串1
2
3s = "helloworld"
print(s.rjust(20)) # -> ' helloworld'
print(s.rjust(20,'*')) # -> '**********helloworld's.zfill(width)
: 返回一个长度为width的字符串,右对齐,前面使用0填充1
2s = "helloworld"
print(s.zfill(20)) # -> 0000000000helloworlds.expandtabs()
:设置制表符的长度 默认为81
2s = "hello\tworld\ta\tb"
print(s.expandtabs()) # hello world a b
搜索字符串
s.count(sub[,start[,end]])
:在指定范围内查找子串的个数1
2
3
4
5s = "helloworld"
print(s.count('l')) # -> 3
print(s.count('lo')) # -> 1
print(s.count('l',5)) # -> 1
print(s.count('l',1,5)) # -> 2s.find(sub[,start[,end]])
在指定范围内查找第一个子串的位置,未找到则返回-11
2
3
4
5s = "helloworld"
print(s.find('l')) # -> 2
print(s.find('L')) # -> -1
print(s.find('l',5)) # -> 8
print(s.find('l',2,5)) # -> 2s.index(sub[,start[,end]])
在指定范围内查找子串的位置,未找到时报错1
2
3s = "helloworld"
print(s.index('l'))
print(s.index('L')) # ValueError: substring not found
替换字符串
s.replace(old,new[,count])
使用new来替换old子串,count用于指定要替换的个数,默认替换所有1
2
3
4s = "helloworld"
print(s.replace('l','a')) # -> heaaoworad
print(s.replace('l','a',1)) # -> healoworld
print("a,b,c,d,e".replace(',','')) # abcdes.strip([chars])
:删除字符串两边的字符,默认是空格1
2
3
4
5s = " Tom "
print(s.strip()) # -> 'Tom'
s = '**Tom**'
print(s.strip('*')) # -> 'Tom's.lstrip([chars]) / s.rstrip([chars])
: 删除左边 或 删除右边的空格或指定的字符1
2
3
4
5s = " Tom "
print(s.lstrip()) # -> 'Tom '
s = '**Tom**'
print(s.lstrip('*')) # -> 'Tom**'
字符串联合
s.join(iterable)
: 使用s来连接可迭代对象生成新的字符串1
print("-".join("abc"))
字符串分隔
s.split(sep,max=-1)
用指定的字符来对原字符串进行分隔
1
2
3s = "hello world haha"
print(s.split()) # ['hello', 'world', 'haha'] # 默认以空格分隔
print(s.split(" ",1)) # ['hello', 'world haha']判断前缀和后缀
s.startswith(prefix)
判断某个字符串是否有某个前缀
1
2s = "http://www.baidu.com"
print(s.startswith('http'))s.endswith(suffix[start,[stop]])
判断是否有某个后缀
1
2s = "http://www.baidu.com"
print(s.endswith('.com'))判断是否是某种类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41# 1. isalpha() 所有字符是否都为字母
s = "abc"
print(s.isalpha()) # True
s = "123"
print(s.isalpha()) # False
s = "abc123"
print(s.isalpha()) # False
# 2. isalnum() 是否都为字母或数字组成
print("abc123".isalnum()) # True
print("abc".isalnum()) # True
print("123".isalnum()) # True
print("123,".isalnum()) # False
# 3. isdigit() 是否为数字 0-9
print("abc".isdigit()) # False
print("123".isdigit()) # True
print("123.123".isdigit()) # False 0-9
print("abc123".isdigit()) # False
# 4. isnumeric() 是否为数字 功能比isdigit强大 计数字符
print("⑵".isnumeric()) # True
print("123".isnumeric()) # True
print("壹".isnumeric()) # True
print("Ⅱ".isnumeric()) # True
print("壹".isdigit()) # False
# 5. isspace() 是否全为空格
print(" ".isspace())
# 6. islower() / isupper() 是否全为小写或大写
print("abc".islower()) # True
print("ABC".islower()) # False
print("ABC".isupper()) # True
print("abc".isupper()) # False
# 7. isdecimal() 是否为十进制的数
print("123".isdecimal()) # True
六、字符串的格式化
在程序中,可能需要得到或输出这样的一个字符串“亲爱的xxx用户你好!你xx月的话费是x”
1 | a = "中国联通" |
在Python中可以使用一种简便的格式化字符串的方式来将某些变量的值插入到固定格式的字符串。
1 | a = "中国联通" |
1 | 1. %d 格式化整数 |
1 | # 特殊用法: |
另一种格式化方式: format
- 形式: “{},{}”.format(参数1,参数2)
- 使用{}来表示占位
1
2
3
4
5
6
7
8
9a = 5
b = 10
c = 20
print("a=%d,b=%d"%(a,b)) # 'a=5,b=10'
print("a={},b={}".format(a,b))
print("a={0},c={2},b={1}".format(a,b,c))
# 关键字参数
print("{url},{name}".format(name="Python教程",url="www.baizhiedu.cn"))Python3.6之后,新加了一种格式化的方式:
1 | a = 50 |