Python:字符串基础

简介

Python 的字符串同 Python 的列表一样,也是序列的一种,可以进行迭代,也可以通过索引访问字符元素,并且 Python 字符串提供了很多非常高效的办法帮助我们进行字符串处理。

Python 字符串常用方法

1. 字符拼接

1.1 join

'string' 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串:

>>> dict_ = ['a', 'b', 'c', 'd', 'e']
>>> '|'.join(dict_)
'a|b|c|d|e'

2. 字符分割:split & partition

2.1 Split

2.1.1 string.split(string="", num=string.count(str))

以 str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num+ 个子字符串


>>> str_ = 'a | b | c | d | e'

>>> str_.split(' | ')
['a', 'b', 'c', 'd', 'e']

>>> str_.split(' | ', 1)
['a', 'b | c | d | e']

rsplit 同理,方向相反

2.1.2 string.splitlines([keepends])

按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符:


>>> lines = 'x\r\ny\rz'

>>> lines.splitlines()
['x', 'y', 'z']

# 如果直接考虑 '\n',则容易因操作系统换行符不同出错
>>> lines.splitlines('\n')
['x\r', 'y\rz']

2.2 partition

2.2.1 string.partition()

以输入的目标字符串为界分为三个部分:[pre_in_string, input, post_in_string],例如:

>>> input = "aaa bbb ccc"
>>> input.partition('bbb')
['aaa ', 'bbb', ' ccc']

# uptime
>>> uptime_output = '18:42:51 up 1:00, 1 user,  load average: 0.08, 0.04, 0.05'
>>> uptime_output.partition('load average: ')
['18:42:51 up 1:00, 1 user,  ', 'load average: ', '0.08, 0.04, 0.05']

3. 字符串格式化

3.1 使用 %s

再字符串中使用变量%s,赋值渲染:

>>> template = '%s nginx 200 %s 500 %s'
>>> template%(2020801, 1000, 200)
'2020801 nginx 200 1000 500 200'

3.2 format

按照 format_map 中参数列表匹配,成功匹配数量必须大于等于模板中的键的数量:

# 不指定键,按顺序填充
>>> "{}|{}".format("hello", "world")
'hello|world'
# 指定顺序
>>> "{2}|{1}".format("world", "hello")
'hello|world'
# 指定字典
>>> template = '{name} is eating {fruit}'
>>> template.format_map({'name': 'somebody', 'fruit':'apple'})
'somebody is eating apple'
# 通过列表
>>> template = '{0[0]} is eating {0[0]}'
>>> name_list = ['somebody', 'apple']
>>> template.format_map(name_list)
'somebody is eating apple'

4. 查找

4.1 find and rfind

>>> string = 'apple'
>>> string.find('p')
1
>>> string.rfind('p')
2
>>> string.find('z')
-1

4.2 index and rindex

>>> string = 'apple'

>>> string.index('p')
1
>>> string.rindex('p')
2

# 区别 find and rfind
>>> string.rindex('o')
ValueError: substring not found
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值