(Python基础数据类型之字符串(一))

一、字符串格式化

1.字符串占位符

# %s 字符串占位
# %d 占位整数
# %f 占位小数

2.字符串格式化操作

# 1.字符串格式化
# 姓名、年龄、地址、爱好
name = input("please enter your name:")
address = input("please enter your address:")
age = int(input("please enter your age:"))
hobby = input("please enter your hobby:")
# s = "我叫%s,我住在%s,我今年%d岁,我喜欢%s" % (name, address, age, hobby)
s1 = "我叫{},我住在{},我今年{}岁,我喜欢做{}".format(name, address, age, hobby)

print(s1)
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/02_字符串.py
please enter your name:kitty
please enter your address:wuhan
please enter your age:18
please enter your hobby:HCIE
我叫kitty,我住在wuhan,我今年18岁,我喜欢HCIE

Process finished with exit code 0

二、f-string格式化

f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串。

# 姓名、年龄、地址、爱好
name = input("please enter your name:")
address = input("please enter your address:")
age = int(input("please enter your age:"))
hobby = input("please enter your hobby:")

# s = "我叫%s,我住在%s,我今年%d岁,我喜欢做%s" % (name, address, age, hobby)
# s1 = "我叫{},我住在{},我今年{}岁,我喜欢做{}".format(name, address, age, hobby)
s2 = f"我叫{name},我住在{address},我今年{age}岁,我喜欢做{hobby}"
print(s2)
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/02_字符串.py
please enter your name:kitty
please enter your address:hangzhou
please enter your age:18
please enter your hobby:HCIE
我叫kitty,我住在hangzhou,我今年18岁,我喜欢做HCIE

Process finished with exit code 0

三、字符串的索引

索引:可以采用索引的方式来提取字符

# 可以采用索引的方式来提取摸个字符
s = "我要学习python"
print(s[3])
print(s[0])
print(s[-1]) #表示倒数
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/03_字符串的索引和切片.py
习
我
n

Process finished with exit code 0

四、字符串的切片

切片:从一个字符串提取一部分内容。

1.常规切片使用方法

s = "我要学习python,还要学习RHCE"
print(s[3:6]) # 从索引3为止切片,到位置6结束,但是拿不到位置6
print(s[0:10])
print(s[:10]) # 从开头切,可以省略
print(s[11:]) # 从开始到结尾切片
print(s[-4:-1]) # 只能从左往右切片
print(s[-1:-4])  # 没有结果

D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/03_字符串的索引和切片.py
习py
我要学习python
我要学习python
还要学习RHCE
RHC

Process finished with exit code 0

3.步长的介绍

其实呢,step在这里表示的是切片的步长(step不能为0,默认为1)。

若 step > 0, 则表示从左向右进行切片。此时,start必须小于end才有结果,否则为空。

若 step < 0, 则表示从右向左进行切片。 此时,start必须大于end才有结果。

2.切片使用方法二

s = "我要学习python,还要学习RHCE"
# 可以给切片添加步长来控制切片的方向
print(s[::-1]) # 负号表示从右往左
m = "adjapwqstm"
print(m[4:9:2])
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/03_字符串的索引和切片.py
ECHR习学要还,nohtyp习学要我
pqt

Process finished with exit code 0