检查字符串中的最后一个字符是否不是L

2024-10-01 09:16:02 发布

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

我有一根这样的绳子:

"A_Origin1_1"

我想删除字符串末尾的所有数字和符号。获得:

^{pr2}$

我可以去掉数字,但不能去掉"_"。我该怎么做?在

这是我目前掌握的代码:

def getNumericTail(str):
    return re.split('[^\d]', str)[-1]

def endsWithNumber(str):
    return bool(getNumericTail(str))

def removeNumericalPortion(str):
    return str[:-1];

## IN MAIN ##
fixedName = "A_Origin1_1"
while endsWithNumber(fixedName) == True:
    fixedName = removeNumericalPortion(fixedName);

Tags: 字符串代码returndef符号数字末尾str
3条回答

只需反转您的方法-而不是删除最后一个字符,如果它是一个数字,删除它如果不是一个字母:

>>> start = "A_Origin1_1"
>>> while start and not start[-1].isalpha():
    start = start[:-1]


>>> start
'A_Origin'

请注意,在while测试中包含start可确保正确处理空字符串;否则,如果删除字符串中的所有字符,它将崩溃:

^{pr2}$

您可能应该看看the style guide;函数名应该是lowercase_with_underscores,而不应该比较{}。在

str1="A_Origin1_1"

while not str1[-1].isalpha():
    str1=str1[:-1]
print (str1)

输出:

^{pr2}$

只是检查字符串的最后一个字符不是字母。While循环将进行处理,直到字符串的最后一个字符是字母。在

您可以使用re.sub

>>> re.sub(r'[\W_\d]+$', r'', "A_Origin1_1")
'A_Origin'

相关问题 更多 >