在Python中,去除字符串最后一个字符可以通过以下几种方法实现:
使用切片操作
def remove_last_character(s):return s[:-1]print(remove_last_character("Hello")) 输出 "Hell"print(remove_last_character("Python")) 输出 "Pytho"
使用字符串的`rstrip()`方法 (如果要去除特定字符):
def remove_last_character(s):return s.rstrip(s[-1])print(remove_last_character("Hello World!")) 输出 "Hello World"

将字符串转换为列表,然后使用`pop()`方法
def remove_last_character(s):return ''.join(list(s)[:len(s)-1])print(remove_last_character("Hello World!")) 输出 "Hello World"
使用`split()`和`join()`方法
def remove_last_character(s):return ''.join(s.split()[:-1])print(remove_last_character("Hello World!")) 输出 "Hello World"
