掌握Python的X篇_24_字符串对象常见方法

本文介绍了如何在Python中进行字符串操作,包括判断文件名前缀和后缀、检查字符串是否为数字、分割与拼接字符串、调整对齐方式以及使用format方法进行格式化,提供实例演示了位置和名称占位法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 判断前缀后缀

In [1]: filename = "shellmad-zhangsan.pdf"

In [2]: filename.endswith(".pdf")
Out[2]: True
In [4]: filename.startswith("shellmad")
Out[4]: True

2. 判断是否是数字

In [1]: str1 = "12345"

In [2]: str2 = "hello"

In [3]: str1.isnumeric()
Out[3]: True

In [4]: str2.isnumeric()
Out[4]: False

3. 将字符串分割为list

我们可以使用字符串对象的split方法,通过指定的分隔符,将字符串分割为一个List

In [5]: mystr =  "shellmad:name:188:27:naneh:xxxx"

In [6]: mylist = mystr.split(":")

In [7]: mylist
Out[7]: ['shellmad', 'name', '188', '27', 'naneh', 'xxxx']

4. 将list拼接为字符串

利用字符串中的join方法,可以将list拼接为字符串

In [8]: "##".join(mylist)
Out[8]: 'shellmad##name##188##27##naneh##xxxx'

5. 对齐调整

字符串对象中有rjust,ljust方法,用于调整字符串的宽度。

In [9]: orgin_str = "hello"

In [10]: orgin_str.rjust(8,"*")
Out[10]: '***hello'
In [12]: orgin_str.ljust(8,"*")
Out[12]: 'hello***'

6. 格式化字符串

python字符串对象中,有format方法,用于格式化字符串。
其中使用”{}”来进行占位,然后通过format方法来传递替换占位符的字符串。
占位常见的方式有两种,按位置,或者按名称

6.1 位置占位

In [15]: str_fmt = "{0} is good one, {1} is another good one"

In [16]:  str_fmt.format("zhangsan","lisi")
Out[16]: 'zhangsan is good one, lisi is another good one'

6.2 名称占位

指定key占位

In [24]: str_fmt = "hi, i am {name},i am {age}, i want {dest}"

In [25]:  str_fmt.format(name="zhangsan",age=16, dest="money")
Out[25]: 'hi, i am zhangsan,i am 16, i want money'

7. 学习视频地址:字符串对象常见方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月旧城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值