1. 程式人生 > >python處理資料——去除字串兩端的引號

python處理資料——去除字串兩端的引號

在用python處理資料,會出現獲得的資料本身兩端帶有引號,而我們需要的是形如xxx,而不是“xxx”否則就會出現問題。比如:
這裡寫圖片描述

『解決方法一:』
使用lstrip()和rsrtip()字串函式

函式說明如下:

str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

具體使用如下:
這裡寫圖片描述

『解決方法二』
先把字元轉換為列表,使用列表的remove函式,再把列表拼成字串

函式說明如下:

array.remove(x)
Remove the first occurrence of x from the array.

但是remove(x)每次只能只能移除x在列表中出現的第一次!所以可能會有副作用,不過對於一個單詞或者短語還是沒有問題的。

具體使用如下:

這裡寫圖片描述

總結:可能還有更多的方法(比如轉換成列表可以定位後刪除),以上兩種方法應該可以應對較多情況。