最近在處理數據的時候,想把一個字符串開頭的“)”符號去掉,所以使用targetStr.lstrip(")"),發現在
將處理完的數據插入到數據庫時會出現編碼報錯,於是在網上搜到了這個帖子。出現上述編碼錯誤問題的原因
是我對lstrip函數的理解錯誤,權威的解釋如下:
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'
strip, lstrip, rstrip的情況都一樣,最重要的是要注意:
參數chars是一個集合,而不是prefix(chars集合中字符的所有組合都會被刪除)
所以分析我出錯的情況:
>>> a = ")" >>> b = "(" >>> a '\xef\xbc\x89' >>> b '\xef\xbc\x88' >>> len(a) 3 >>> a.lstrip(b) '\x89' >>> b.lstrip(a) '\x88' >>> targetStr = ")求教python高手:(一)" >>> print targetStr.lstrip(a) 求教python高手:(一) >>> print targetStr.lstrip(b) �求教python高手:(一) >>> targetStr = "(1)求教python高手:(一)" >>> print targetStr.lstrip(a) �1)求教python高手:(一) >>> print targetStr.lstrip(b) 1)求教python高手:(一)
所以我采用的解決方法如下,
方法1:
>>> targetStr = ")求教python高手:(一)" >>> targetStr = targetStr[3:] if targetStr.find(")") == 0 else targetStr >>> print targetStr 求教python高手:(一) >>> targetStr = "(1)求教python高手:(一)" >>> targetStr = targetStr[3:] if targetStr.find(")") == 0 else targetStr >>> print targetStr (1)求教python高手:(一)
方法2:
>>> len(u")") 1 >>> targetStr = u")求教python高手:(一)" >>> print targetStr )求教python高手:(一) >>> targetStr u'\uff09\u6c42\u6559python\u9ad8\u624b\uff1a\uff08\u4e00\uff09' >>> targetStr = targetStr.lstrip(u")") >>> targetStr u'\u6c42\u6559python\u9ad8\u624b\uff1a\uff08\u4e00\uff09' >>> print targetStr 求教python高手:(一) >>> targetStr = u"(1)求教python高手:(一)" >>> print targetStr (1)求教python高手:(一) >>> targetStr u'\uff081\uff09\u6c42\u6559python\u9ad8\u624b\uff1a\uff08\u4e00\uff09' >>> targetStr = targetStr.lstrip(u")") >>> targetStr u'\uff081\uff09\u6c42\u6559python\u9ad8\u624b\uff1a\uff08\u4e00\uff09' >>> print targetStr (1)求教python高手:(一)
如果各位有更好的方法,一定要告訴我 : )
此外,從這個帖子我還學習到了另外一點:
>>> c = int("\t22\n") >>> c 22
References:
求教python高手:一個簡單的問題,lstrip函數切割錯誤