替换字符串末尾的字符?

2024-09-27 00:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python工作,我有一个字符串,比如"world's" and "states.'",我想检查单词的最后一个字母是否是字母表,如果不是,就删除它。我有以下代码:

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

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


Tags: and字符串代码worldif字母字符单词
3条回答

或者一个好的旧regexp:

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

尝试循环:

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

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

输出:

"'foo"

String的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

相关问题 更多 >

    热门问题