字符串,顾名思义就算是以一串字母数字命名的字符。
字符串的运用:
1.查看字符串的长度:len()命令,利用我们上节课说过的print输出函数,print(len(字符串’))就可以输出字符串的长度了。
2.字符串的拼接 word4 = 'Hello ', word5 = 'world',word6 =word4 +word5,两个字符串可以直接相加赋予给新的变量,就可以拼接了
3.字符串的复制,简单来说就是直接把一个字符串打印n遍:word7 = 'world' ,word8 = 'world' * n
4.字符串的访问字符串,索引是一个数字,用于标识字符在字符串的位置,索引从0开始,从左向右数,比如有一个字符串python,它的每一个索引对应一个字符
![](https://img-blog.csdnimg.cn/20210729140136533.png)
如果想访问第y这个字母可以这样写:
str1 = 'python’
str2 = str[1]
print(str2)
索引不可以越界,‘python’字符串中是从0到5,最大只能索引到5,如果索引输入6的话,程序就会报错
想取n的话也可以从(-1)开始取,负索引,是倒着取的,与正索引不同的是,正索引是从0开始的,负索引是从-1开始取的
字符串切片
切片可以理解为在索引的基础上拓展的,索引可取的是一个,切片则可以取一个索引区间的内容。下边代码演示
str1 = 'python’
str2 = str[1:5]
print(str2)
切片取索引1~5但不包含5的字符
5,步长
字符串切片的完整表达式其实是这样的:
string[index1:index2:step]
index1,index2 分别表示你要切片区间的数字,step 就是步长,步长默认为1,可省略不写,像上边这个字符串切片,str2 = str[1:5],就省略了步长
步长可以正取,也可倒着取,正负号就代表取的方向。
step(步长)的值
step1与step2的区别:
str3
=
'Hello Python'
str4
=
str3
[
0
:
12
:
1
]
str5
=
str3
[
0
:
12
:
2
]
print(str4)
print(str5)
6,字符串的查找
一般用in/not in
in
用来判断一个字符串是否在包含着另一个字符串中,
而
not in
用来判断一个字符串是否在不包含着另一个字符串中
word1
=
"i like python
"
word2
=
"
python
"
word3 = '我喜欢学习'
print
(
word1
in
word2
)
#
判断笨蛋这个词语是否在
word2
这句话里面
print
(
word1
not in
word2
)
#
判断笨蛋这个词语是否不在
word2
这句画里面
结果会返回一个布尔值
find
查找某一字符是否存在于另个字符串中时, 如果存在则返回该字符串在另一个字符串中第
一次出现时第一个字符的所在位置, 如果不存在则返回
-1
。
index
=
word2
.
find
(
word1
)
#
表示查找
word2
中是否有
word1,
print
(
index
)
index2
=
word3
.
find
(
word2
)
#
表示查找字符串
word3
中是否有
word1
print
(
index2
)
7字符串替换
replace
str1 = word3.replace(''学习'', ''**'')
print(word3)
print(str1)
8字符串分割
words
=
"I really like my bike"
result2
=
words
.
split
(
" "
)
#
表示以空格分割,分割的值并以列表形式返回
print
(
result2
)
9字符串格式化
template
=
'Hello {}' #要替换的地方先用空格表示
message
=
template
.
format
(
"Tom"
)
#把上边的大括号替换成Tom,当然你们想换成其它也是可以
print
(
message
)
字符串格式化也可以替换多个位置
template3
=
"{} and {}"
.
format
(
'Jack'
,
'Tom'
)
template4
=
"
{0}
and
{1}
"
.
format
(
'Jack'
,
'Tom'
)
#0表示Jack,1表示Tom
template5
=
"
{1}
and
{0}
"
.
format
(
'Jack'
,
'Tom'
)
print
(
template3
)
print
(
template4
)
print
(
template5
)
也可以通过名称替换内容
template7
=
'I am
{name}
,and
{age}
years old.'
.
format
(
age
=
10
,
name
=
'Tom'
)
print
(
template7
)
也可以对替换的内容做特殊处理
'{0:.2f}, {1:.3f}'
.
format
(
3.14159
,-
2.57896
)
#0,1分别表示.format后面的那两个数 .2f/.3f分别表示保留几位小数点
"{:.2%}"
.
format
(
0.25
)
#
表示保留两位小数,百分号表示以百分比的形式显示。
"{:.0%}"
.
format
(
0.25
)
#
表示不包含小数部
10,转义字符
分。
数字与字母的关系
1字符转数字
ord(字符)
2数字转字符
chr(数字)