如何从字符串的末尾删除子字符串? [英] How do I remove a substring from the end of a string?

查看:55
本文介绍了如何从字符串的末尾删除子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

url = 'abcdc.com'
print(url.strip('.com'))

我期望:abcdc

我得到:abcd

现在我做

url.rsplit('.com', 1)

有没有更好的方法?

推荐答案

strip 并不意味着删除这个子字符串".x.strip(y)y 视为一组字符,并从 x 的两端去除该集合中的任何字符.

strip doesn't mean "remove this substring". x.strip(y) treats y as a set of characters and strips any characters in that set from both ends of x.

Python 3.9 和更新版本上,您可以使用 removeprefixremovesuffix 从字符串的任一侧删除整个子字符串的方法:

On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string:

url = 'abcdc.com'
url.removesuffix('.com')    # Returns 'abcdc'
url.removeprefix('abcdc.')  # Returns 'com'

相关的 Python 增强提案是 PEP-616.

The relevant Python Enhancement Proposal is PEP-616.

Python 3.8 及更早版本上,您可以使用 endswith 和切片:

On Python 3.8 and older you can use endswith and slicing:

url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]

正则表达式:

import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)

这篇关于如何从字符串的末尾删除子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆