1.介绍
是一种用来表示文本的数据类型,由字符号或数值组成的一个连续序列
(1)定义
定义 | 用处 | 例子 |
单引号 | 定义单行字符串 | 'hello itcast' |
双引号 | 定义单行字符串 | "hello itcast" |
三引号 | 定义多行字符串 | """my name is itcast my name is itcast""" |
(2)转义
使用反斜杠“\”转义
print('let\'s learn Python')
let's learn Python
2.格式化字符串
(1)%
format % values
(2)format()
str.format(values)
(3)f-string
f('{变量名}') 或F('{变量名}')
3.查找与替换
(1)查找
find()可以查找字符串中是否包含子串,若包含则返回子串首次出现的位置,否则返回-1
str.find(sub[, start[, end]])
word = 't'
string = 'Python'
result = string.find(word)
print(result)
2
(2)替换
replace()可以将当前字符串中的指定子串替换成新的子串,并返回替换后的新字符串
str.replace(old, new[, count])
string = 'He said, "you have to go forward, ' \
'Then turn left, Then go forward, and Then turn right."'
# 指定替换两次
new_string = string.replace("Then", "then",2)
print(new_string)
He said, "you have to go forward, then turn left,
then go forward, and Then turn right."
4.分隔与拼接
(1)分割
split()可以按照指定分隔符对字符串进行分割,该方法会返回由分割后的子串组成的列表
str.split(sep=None, maxsplit=-1)
string= "Hello, my name is Wang Hong"
# 以空格作为分割符,并分割2次
print(string.split(' ', 2))
['Hello,', 'my', 'name is Wang Hong']
(2)拼接
join()使用指定的字符连接字符串并生成一个新的字符串
str.join(iterable)
symbol = '*'
world = 'Python'
print(symbol.join(world))
P*y*t*h*o*n
还可以使用“+”拼接
"py" + "thon" = "python"
5.删除
6.对齐