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

举报
江湖有缘 发表于 2023/07/13 10:53:42 2023/07/13
871 0 0
【摘要】 Python基础数据类型之字符串(一)

@TOC

一、字符串格式化

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
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。