[英]Python remove last character of string if its a letter
How do I remove the last character of a string if its a letter. 如何删除字符串的最后一个字母(如果是字母)。
eg if I had the following strings. 例如,如果我有以下字符串。
my_string = 'ABC 1.1 A'
my_string2 = 'ABC 1.1 B'
my_string3 = 'DEF 1'
I would want my_string = 'ABC 1.1'
, my_string2 = 'ABC 1.1'
, and my_strin3 = 'DEF 1'
我想要my_string = 'ABC 1.1'
, my_string2 = 'ABC 1.1'
和my_strin3 = 'DEF 1'
These strings are generated from DB so it would not be a manual process. 这些字符串是从数据库生成的,因此它不是手动过程。
You can use str.rstrip()
: 您可以使用str.rstrip()
:
import string
my_string = my_string.rstrip(string.ascii_letters + string.whitespace)
This will remove all letters and whitespace characters from the end of the string. 这将从字符串末尾删除所有字母和空格字符。
try this: 尝试这个:
import string
if my_string[-1] in string.ascii_letters:
my_string = my_string[0:-1].strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.