求助,字符串removeprefix()和removesuffix()怎么使用
本帖最后由 挑灯. 于 2021-3-5 13:34 编辑我在论坛中找到如图的介绍,但是我输入这个方法却会报错,请问这个用法该如何使用?
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul8 2019, 20:34:20) on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
=================== RESTART: C:\Users\13217\Desktop\测试.py ===================
>>> str1='aassdd'
>>> str1.removeprefix('aa')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str1.removeprefix('aa')
AttributeError: 'str' object has no attribute 'removeprefix'
>>> str1.removeprefix('dd')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
str1.removeprefix('dd')
AttributeError: 'str' object has no attribute 'removeprefix'
>>> 'aassdd'.removeprefix('aa')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
'aassdd'.removeprefix('aa')
AttributeError: 'str' object has no attribute 'removeprefix'
>>> 'aassdd'.removeprefix('dd')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
'aassdd'.removeprefix('dd')
AttributeError: 'str' object has no attribute 'removeprefix' 这是py3.9才有的字符串方法 hrp 发表于 2021-3-5 13:35
这是py3.9才有的字符串方法
所以只能升级版本才能使用吗{:5_96:} 本帖最后由 hrp 于 2021-3-5 15:06 编辑
挑灯. 发表于 2021-3-5 13:35
所以只能升级版本才能使用吗
对。不过用不了也无所谓了,自己写功能一样的函数也是十分简单的。
def removeprefix(string, prefix):
if not (isinstance(string, str) and isinstance(prefix, str)):
raise TypeError('Param value type error')
if string.startswith(prefix):
return string
return string
def removesuffix(string, suffix):
if not (isinstance(string, str) and isinstance(suffix, str)):
raise TypeError('Param value type error')
if string.endswith(suffix):
return string[:-len(suffix)]
return string
# 测试
s = 'aadjjfkkdiio'
print(removeprefix(s, 'aad'))
print(removesuffix(s, 'iio'))
hrp 发表于 2021-3-5 14:59
对。不过用不了也无所谓了,自己写功能一样的函数也是十分简单的。
好吧 谢谢大佬
页:
[1]