Python strip()、join()、split()函数用法

在对数据做预处理时可能会用到对字符串操作的函数,这几个函数的功能都是在操作字符串,下面逐个介绍。

一.strip()

  • 语法:
str.strip([chars]);
  • 参数说明
    chars:指定要移除的字符串首位的字符或字符串

函数的作用是,移除字符串头尾指定的字符chars生成新字符串。

例子1:

str = '123hello world!'
str.strip('123')

输出:

 'hello world!'

例子2:

str = "00000003210Runoob01230000000"
print(str.strip('0') )

str2 = "   Runoob      " 
print(str2.strip()) # 参数为空,默认去除首位空格

输出:

3210Runoob0123
Runoob

二、join()

  • 语法:
'sep'.join(seq)
  • 参数说明
    sep:分隔符。可以为空
    seq:要连接的元素序列、字符串、元组、字典

上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串。

例子1:

"""对序列进行操作(分别使用' '与':'作为分隔符)
"""
>>> seq1 = ['hello', 'world', 'hello', 'python']
>>> ' '.join(seq1)
hello world hello python
>>> print ':'.join(seq1)
hello:world:hello:python

例子2:


"""对字符串进行操作
"""
>>> seq2 = 'hello world hello python'
>>> ':'.join(seq2)
'h:e:l:l:o: :w:o:r:l:d: :h:e:l:l:o: :p:y:t:h:o:n'

例子3:

"""对元组进行操作
"""
>>> seq3 = ('hello', 'world', 'hello', 'python')
>>> ' '.join(seq3)
'hello world hello python'

例子4:

"""对字典进行操作
"""
>>> seq4 = {'hello':1, 'world':2, 'hello':3, 'python':4}
>>> '!'.join(seq4)
'hello!world!python'

三、split()

  • 语法
str.split(str="", num=string.count(str)).
  • 参数说明
    str:分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
    num:分割次数。

作用是将字符串按着自己指定的字符或字符串作为分隔符,从左至右分割num次,最后返回一个列表。
若未指定分割数,则按指定字符或字符串分隔整个字符串。

例子:

>>> str1 = '   hello world hello python'
>>> str1.split(' ')
['', '', '', 'hello', 'world', 'hello', 'python']
>>> str = '   hello world hello python'
>>> str.split(' ', 4)
['', '', '', 'hello', 'world hello python']

有关split()对数据做预处理的进阶使用,请参照网站:
http://www.runoob.com/python/att-string-split.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值