1. 程式人生 > >Python處理字串

Python處理字串

環境python2.7—修改時間20170302

刪除字串空格

使用字串函式strip等刪除兩端空格

"   xyz   ".strip()           # returns "xyz"
"   xyz   ".lstrip()          # returns "xyz   "
"   xyz   ".rstrip()          # returns "   xyz"

使用字串函式replace刪除所有空格

"  x y z  ".replace(' ', '')  # returns "xyz"

使用正則表示式刪除空格

import re
re.sub(r' '
, '', " x y z ") # returns "xyz"

分割字串

使用字串函式split分割字串

"x  y  z".split(' ')          # returns ['x', '', 'y', '', 'z']

使用正則表示式刪除空格

使用split難以分割連續空格,正則表示式可以很好解決

import re
re.split(r'\s+', "x  y  z")   # returns ['x', 'y', 'z']

列表中字元元素轉為數字

使用迴圈的方法

num_str = ['1', '2', '3']
num = []
for
i in num_str: num.append(int(i)) #num = [1, 2, 3]

使用列表生成式

num_str = ['1', '2', '3']
num = [int(x) for x in num_str]
#num = [1, 2, 3]

使用map對映函式

這種方法抽象程度高,使用更方便

num_str = ['1', '2', '3']
num = map(int, num_str)
#num = [1, 2, 3]