Python String removesuffix() 方法

2025年1月5日 | 阅读 2 分钟

引言

在本教程中,我们将学习 Python 字符串中的 removesuffix() 方法。如果字符串以 suffix 结尾且 suffix 非空,则使用 str.removessuffix(suffix, /) 函数移除 suffix 并返回给定字符串的剩余部分。如果找不到 suffix 字符串,则返回原始字符串。它是在 Python 3.9.0 版本中引入的。

语法

Python 字符串 removesuffix() 方法的语法如下:

参数

Python 字符串 removesuffix() 方法的参数如下:

  • suffix: 我们正在检查的后缀字符串。

返回值

string [: → len (suffix)] 如果字符串以 suffix 结尾且 suffix 非空。否则,返回原始字符串的副本。

程序代码 1

这里我们提供了 Python 字符串 removesuffix() 方法的程序代码。代码如下:

输出

现在,我们运行上述代码并从中找到输出。输出如下:

Hello everyone, welcome to 
Hello everyone, welcome to javatpoint

程序代码 2

这里我们提供了 Python 字符串 removesuffix() 方法的程序代码。Python 字符串 removesuffix() 方法会移除字符串的后缀(如果存在),否则返回原始字符串。代码如下:

输出

现在,我们运行上述代码并从中找到输出。输出如下:

The given string 1 is:  Hello everyone, welcome to javatpoint
The new string is:  Hello everyone, welcome to javatpoint
The given string 2 is:  Welcome Here
The new string is:  Welcome

结论

在本教程中,我们将学习 removesuffix() 方法在 Python 字符串中的用法。我们将学习 removesuffix() 方法的语法、参数和返回值。还将分享该方法的一些程序代码。