1. 程式人生 > >Python strip()、join()、split()函式用法

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']