我在Python工作,我有一個字符串,如"world's" and "states.'"
,我想檢查該單詞的最後一個字母是否是字母表,如果不是,請將其刪除。我有以下代碼:替換字符串末尾的字符?
if word[-1].isalpha():
print word
else:
print word[:-1]
但我也希望能夠刪除兩個(或更多)非字母字符。我知道我需要某種循環。
我在Python工作,我有一個字符串,如"world's" and "states.'"
,我想檢查該單詞的最後一個字母是否是字母表,如果不是,請將其刪除。我有以下代碼:替換字符串末尾的字符?
if word[-1].isalpha():
print word
else:
print word[:-1]
但我也希望能夠刪除兩個(或更多)非字母字符。我知道我需要某種循環。
字符串的rstrip
函數可以選擇刪除一個字符列表。
rstrip(...)
S.rstrip([chars]) -> string or unicode
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
嘗試循環:
def rstripNotalpha(s):
while not s[-1].isalpha():
s = s[:-1]
return s
s = "'foo.-,'"
print(rstripNotalpha(s))
輸出:
"'foo"
還是不錯的老正則表達式:
import re
p = re.compile('(.*\w)([^\w]*)')
m = p.match(word)
print m.group(1)
這是真實的,但'chars'是一個黑名單。白名單將需要。 – 2014-10-09 08:20:17