2014-10-09 126 views
2

我在Python工作,我有一个字符串,如"world's" and "states.'",我想检查该单词的最后一个字母是否是字母表,如果不是,请将其删除。我有以下代码:替换字符串末尾的字符?

if word[-1].isalpha(): 
    print word 
else: 
    print word[:-1] 

但我也希望能够删除两个(或更多)非字母字符。我知道我需要某种循环。

回答

0

字符串的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 
+0

这是真实的,但'chars'是一个黑名单。白名单将需要。 – 2014-10-09 08:20:17

4

尝试循环:

def rstripNotalpha(s): 
    while not s[-1].isalpha(): 
     s = s[:-1] 
    return s 

s = "'foo.-,'" 
print(rstripNotalpha(s)) 

输出:

"'foo" 
0

还是不错的老正则表达式:

import re 
p = re.compile('(.*\w)([^\w]*)') 
m = p.match(word) 
print m.group(1)