字符串
1. 什么是字符串(str)
- 字符串是python自带的容器型数据类型;将’'或者""作为容器的标志,里面的每一个符号都是字符串的元素
- 字符串是不可变的;字符串是有序的
- 任何文字符号都可以作为字符串的元素
str1 = 'mK1,和。😊'
print(str1)
str2 = ''
2. 转义字符
字符串中每个独立的符号就是字符串的元素,又叫字符。
字符分为两类:
1)普通字符 - 在字符串中表示符号本身的字符
2)转义字符 - 在特定的符号前加\表示特殊功能或者特殊意义的字符
\n | 换行 |
---|---|
\t | 水平制表符(按一次tab键) |
\’ | 表示一个普通的单引号 |
" | 表示一个普通的双引号 |
\ | 表示一个普通的反斜杠 |
str1 = '\\tmn\\n12吗'
print(str1)
str1 = 'it\\'s me'
print(str1)
str1 = "it's me"
print(str1)
str1 = "i say:\\"good good study!day day up!\\""
print(str1)
str1 = 'i say:"good good study!day day up!"'
print(str1)
str1 = '\\\\name'
print(str1)
3. r字符串
在字符串的最前面加r/R,可以让字符串中所有的转义字符功能消失(让字符串中所有的字符都变成普通字符)
str1 = r'\\tabc\\n123\\'你好'
print(str1)
str1 = r'C:\\home\\names\\test\\demo\\best\\a.txt'
print(str1)
4. 查 - 获取字符
1)查单个: 字符串[索引]
message = '\\thello\\npython!'
print(message[-1])
print(message[1])
2)切片: 字符串[开始下标:结束下标]
print(message[1:6])
print(message[-7:])
3)遍历
for x in message:
print(x)
for x in range(len(message)):
print(x, message[x])
5. 字符串相关操作
1)数学运算
字符串1 + 字符串2 - 将两个字符串合并成一个字符串
字符串 * N - 将字符串内容重复N次产生一个新的字符串
str1 = '数据分析'
str2 = 'python'
result = str2 + str1
print(result)
# 案例:在str1中每个数字的后面插入一个'+'
str1 = 'mn23ks9技术0了'
# 'mn2+3+ks9+技术0+了'
new_str = ''
for x in str1:
if '0' <= x <= '9':
new_str += x + '+'
else:
new_str += x
print(new_str)
# 练习1:提取字符串str1中所有的小写字母
str1 = 'mn23ks9技MK术p0了Kn'
new_str = ''
for x in str1:
if 'a' <= x <= 'z':
new_str += x
print(new_str)
# 练习2:将字符串str1中所有的大写字母替换成'-'
str1 = 'mn23ks9技MK术p0了Kn'
new_str = ''
for x in str1:
if 'A' <= x <= 'Z':
new_str += '-'
else:
new_str += x
print(new_str)
# 练习3:删除字符串str1中所有的字母
str1 = 'mn23ks9技MK术p0了Kn'
new_str = ''
for x in str1:
if not ('a' <= x <= 'z' or 'A' <= x <= 'Z'):
new_str += x
print(new_str)
str1 = 'a' * 10
print(str1)
str1 = 'abc' * 3
print(str1)
2)in 和 not in
字符串1 in 字符串2 - 判断字符串1是否是字符串2的子串(判断字符串2中是否包含字符串1)
str1 = 'hello python'
print('h' in str1)
print('he' in str1)
print('hl' in str1) # False
字符串的相关方法
1.字符串.join(容器)
将容器中的元素用指定的字符串拼接成一个新的字符串。(容器中的元素必须全是字符串)
list1 = ['python', 'java', 'c', 'php', 'go']
result = '+'.join(list1)
print(result) # 'python+java+c+php+go'
str1 = 'abc'
result = ' And '.join(str1)
print(result)
2.字符串1.replace(字符串2, 字符串3)
将字符串1中所有的字符串2都替换成字符串3
str1 = 'how are you? i am fine! thank you! and you?'
result = str1.replace('you', 'me')
print(result) # how are me? i am fine! thank me! and me?
result = str1.replace('you', 'me', 2)
print(result) # how are me? i am fine! thank me! and you?
3.字符串1.split(字符串2)
将字符串1中所有的字符串2作为切割点对字符串进行切割
str1 = 'how are you? i am fine! thank you! and you?'
result = str1.split('you')
print(result)
result = str1.split('you', 2)
print(result)
4.字符串1.count(字符串2)
统计字符串1中字符串2出现的次数
print(str1.count('you'))
5.f-string
将变量中的内容拼接到字符串中
在字符串的最前面加f/F,就可以在字符串中通过{表达式}来提供字符串内容
name = '小明'
age = 18
print(f'{name}今年{age}岁!')
str1 = f'{name[-1]}今年{age + 10}岁!'
print(str1)
a = 100
b = 200
print(f'a:{a}, b:{b}')
print(f'{a}+{b}={a+b}')