关于python字符串的知识

Python字符串操作详解
本文介绍了Python字符串的基础知识,包括字符串的列表性质、索引与切片操作,字符串转列表、字符提取以及字符串反转的方法。此外,还展示了字符串的连接、转义字符的使用以及格式化输出。通过实例演示了字符串的切片、反转和格式化,帮助读者深入理解Python字符串的运用。

1. 字符串的实质

字符串实质上是一个列表,可以通过索引来取得其中的某个字符.索引从 0 开始。
python 可以取负值,表示从末尾提取,最后一个为 -1,倒数第二个为 -2,即程序认为可以从结束处反向计数。
示意图:在这里插入图片描述

运用:

- 将字符串转换为一个个单独的字符列表

str_1 = 'windows_123'
str_2 = list(str_1)
print("%s" % str_2)

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
['w', 'i', 'n', 'd', 'o', 'w', 's', '_', '1', '2', '3']

- 获取其中的某个字符:

str_1 = 'windows_123'
print("%s" % str_1[5])

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
w

- 字符串切片:

字符串[开始索引:结束索引:步长]
切取字符串为开始索引到结束索引-1内的字符串,即字符串长度为 (结束索引-开始索引)
默认参数:
当开始索引不指定时,默认为开始位置0.
当结束索引不指定时,默认为结束位置-1.
当步长不指定时,默认步长为1.

str_1 = 'windows_123'
str_2 = str_1[:]
str_3 = str_1[::]
str_4 = str_1[2:]
str_5 = str_1[:4]
str_6 = str_1[0:-1:2]
str_7 = str_1[0:len(str_1):2]
print("%s\n%s\n%s\n%s\n%s\n%s" % (str_2, str_3, str_4, str_5, str_6, str_7))

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
windows_123
windows_123
ndows_123
wind
wnos1
wnos13

2. 关于字符串的一些小知识点

- 字符串中加引号,斜杠:加转义符号" \ "

str_1 = 'window\'s_123'
str_2 = 'window\"s_123'
str_3 = 'window\\s_123' 
print("%s\t%s\t%s" % (str_1, str_2,str_3))

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
window's_123    window"s_123    window\s_123

- 字符串可以相加:运用"+",使得两个字符串连在一起

str_1 = 'window\'s_123'
str_2 = 'window\"s_123'
print("%s" % (str_1 + str_2))

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
window's_123window"s_123

- 字符串倒序:

方法一:

运用函数reverse(),注意需要将字符串先转换为列表,字符串无法进行此操作

str_1 = 'python'
str_1 = list(str_1)
str_1.reverse()
result = ''.join(str_1)
print("%s\n%s" % (str_1, result))

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
['n', 'o', 'h', 't', 'y', 'p']
nohtyp

声明:join方法
大概意思是:s.join(iterable)是将括号内的迭代对象(如列表)使用s字符串作为链接将迭代对象中的元素拼接成一个字符串,返回该字符串

方法二:
运用字符串切片

str_1 = 'python'
print("%s" % str_1[::-1])

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
nohtyp

- 字符串格式化

看自己整理的这一篇文章:
https://blog.youkuaiyun.com/mjfppxx/article/details/113744502

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值