我有一根这样的绳子:
"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);
只需反转您的方法-而不是删除最后一个字符,如果它是一个数字,删除它如果不是一个字母:
请注意,在
^{pr2}$while
测试中包含start
可确保正确处理空字符串;否则,如果删除字符串中的所有字符,它将崩溃:您可能应该看看the style guide;函数名应该是}。在
lowercase_with_underscores
,而不应该比较{输出:
^{pr2}$只是检查字符串的最后一个字符不是字母。While循环将进行处理,直到字符串的最后一个字符是字母。在
您可以使用
re.sub
相关问题 更多 >
编程相关推荐