Python字符串 – removesuffix()
如果字符串以后缀结尾并且后缀不为空,则str.removesuffix(suffix, /)函数将删除后缀并返回字符串的其余部分。如果未找到后缀字符串,则返回原始字符串。它是在Python 3.9.0 版本中引入的。
Syntax: str.removesuffix(suffix, /)
Parameters:
Suffix– suffix string that we are checking for.
Return value:
Returns: string[ : – len (suffix) ] if the string ends with suffix string and that suffix is not empty. Else it returns the copy of original string.
示例 1:
Python3
# Python 3.9 code explaining
# str.removesuffix()
# suffix exists
print('ComputerScience'.removesuffix('Science'))
# suffix doesn't exist
print('GeeksforGeeks'.removesuffix('for'))
Python3
# Python 3.9 code explaining
# str.removesuffix()
# String for removesuffix()
# If suffix exists then
# then it remove suffix from the string
# otherwise return original string
string1 = "Welcome to python 3.9"
print("Original String 1 : ", string1)
# suffix exists
result = string1.removesuffix("3.9")
print("New string : ", result)
string2 = "Welcome Geek"
print("Original String 2 : ", string2)
# suffix doesn't exist
result = string2.removesuffix("Welcome")
print("New string : ", result)
输出:
Computer
GeeksforGeeks
示例 2:
蟒蛇3
# Python 3.9 code explaining
# str.removesuffix()
# String for removesuffix()
# If suffix exists then
# then it remove suffix from the string
# otherwise return original string
string1 = "Welcome to python 3.9"
print("Original String 1 : ", string1)
# suffix exists
result = string1.removesuffix("3.9")
print("New string : ", result)
string2 = "Welcome Geek"
print("Original String 2 : ", string2)
# suffix doesn't exist
result = string2.removesuffix("Welcome")
print("New string : ", result)
输出:
Original String 1 : Welcome to python 3.9
New string : Welcome to python
Original String 2 : Welcome Geek
New string : Welcome Geek