从字符串末尾删除子字符串可以通过以下几种方法实现:
string = "abcdefgabc"
substring = "abc"
new_string = string[:-len(substring)]
print(new_string)
输出结果为:"abcdefg"
string = "abcdefgabc"
substring = "abc"
new_string = string.replace(substring, "")
print(new_string)
输出结果为:"defg"
import re
string = "abcdefgabc"
substring = "abc"
pattern = re.compile(re.escape(substring) + "$")
new_string = re.sub(pattern, "", string)
print(new_string)
输出结果为:"abcdefg"
以上是三种常见的方法来从字符串末尾删除子字符串的方式。根据具体的需求和场景,选择适合的方法即可。
领取专属 10元无门槛券
手把手带您无忧上云