在对数据做预处理时可能会用到对字符串操作的函数,这几个函数的功能都是在操作字符串,下面逐个介绍。
一.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
本文详细介绍了Python中常用的字符串操作函数strip(), join()和split()。通过实例演示了如何使用这些函数进行数据预处理,如去除字符串首尾特定字符、连接序列元素、以及按指定字符分割字符串。
3098

被折叠的 条评论
为什么被折叠?



