Python 字符串 – removeprefix() 函数 您所在的位置:网站首页 removeprefix Python 字符串 – removeprefix() 函数

Python 字符串 – removeprefix() 函数

2023-12-26 22:55| 来源: 网络整理| 查看: 265

在本文中,我们将使用 str.removeprefix(prefix, /) 函数删除前缀并返回字符串的其余部分。如果找不到前缀字符串,则返回原始字符串。在 Python 3.9.0 版本中引入。

语法:

str.removeprefix(prefix, /)

参数:

suffix- prefix string that we are checking for.

返回值:

返回 string[len(prefix):] 否则返回原始字符串的副本。

代码:

示例 1:

Python3实现

# Python 3.9 code explaining  # str.removeprefix()   s = 'GeeksforGeeks'   # prefix exists print(s.removeprefix('Geeks')) print(s.removeprefix('G'))     # whole string is a prefix # it would print an empty string print(s.removeprefix('GeeksforGeeks'))   # prefix doesn't exist # whole string is returned print(s.removeprefix('for')) print(s.removeprefix('IT')) print(s.removeprefix('forGeeks'))

输出:

forGeeks eeksforGeeks

GeeksforGeeks GeeksforGeeks GeeksforGeeks

示例 2:

Python3实现

# Python 3.9 code explaining  # str.removeprefix()   # String for removeprefix()  # If prefix exists then  # remove prefix from the string  # otherwise return original string      string1 = "Welcome to python 3.9" print("Original String 1 : ", string1)      # prefix exists  result = string1.removeprefix("Welcome")  print("New string : ", result)      string2 = "Welcome Geek" print("Original String 2 : ", string2)      # prefix doesn't exist  result = string2.removeprefix("Geek")  print("New string : ", result)

输出:

Original String 1 : Welcome to python 3.9 New string : to python 3.9 Original String 2 : Welcome Geek New string : Welcome Geek


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有