我有以下代码:
url = 'abcdc.com'
print(url.strip('.com'))
我以为是abcdc
我得到:abcd
现在我知道了
url.rsplit('.com', 1)
有没有更好的办法?
参见.strip/.rstrip/。lstrip字符串方法在Python中工作?对于第一次尝试的具体解释。
我有以下代码:
url = 'abcdc.com'
print(url.strip('.com'))
我以为是abcdc
我得到:abcd
现在我知道了
url.rsplit('.com', 1)
有没有更好的办法?
参见.strip/.rstrip/。lstrip字符串方法在Python中工作?对于第一次尝试的具体解释。
当前回答
因为似乎还没有人指出这一点:
url = "www.example.com"
new_url = url[:url.rfind(".")]
这应该比使用split()的方法更有效,因为不会创建新的列表对象,而且这种解决方案适用于带有几个点的字符串。
其他回答
Strip并不是指“删除这个子字符串”。x.strip(y)将y视为一个字符集,并从x的两端剥离该字符集中的任何字符。
在Python 3.9及更新版本中,您可以使用removeprefix和removesuffix方法从字符串的任意一侧删除整个子字符串:
url = 'abcdc.com'
url.removesuffix('.com') # Returns 'abcdc'
url.removeprefix('abcdc.') # Returns 'com'
相关的Python增强提案是PEP-616。
在Python 3.8及以上版本中,你可以使用endswith和slicing:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
或者正则表达式:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
假设你想删除域名,不管它是什么(.com, .net等)。我建议找到。并从那一刻起移除一切。
url = 'abcdc.com'
dot_index = url.rfind('.')
url = url[:dot_index]
在这里,我使用rfind来解决像abcdc.com这样的url的问题,它应该被简化为abcdc.com的名称。
如果你也关心www.s,你应该明确地检查它们:
if url.startswith("www."):
url = url.replace("www.","", 1)
replace中的1用于奇怪的边例,例如www.net.www.com
如果你的url比这更乱,看看人们用正则表达式回答的问题。
一个更广泛的解决方案,增加替换后缀的可能性(你可以用空字符串替换),并设置替换的最大数量:
def replacesuffix(s,old,new='',limit=1):
"""
String suffix replace; if the string ends with the suffix given by parameter `old`, such suffix is replaced with the string given by parameter `new`. The number of replacements is limited by parameter `limit`, unless `limit` is negative (meaning no limit).
:param s: the input string
:param old: the suffix to be replaced
:param new: the replacement string. Default value the empty string (suffix is removed without replacement).
:param limit: the maximum number of replacements allowed. Default value 1.
:returns: the input string with a certain number (depending on parameter `limit`) of the rightmost occurrences of string given by parameter `old` replaced by string given by parameter `new`
"""
if s[len(s)-len(old):] == old and limit != 0:
return replacesuffix(s[:len(s)-len(old)],old,new,limit-1) + new
else:
return s
在您的情况下,给定默认参数,将获得所需的结果:
replacesuffix('abcdc.com','.com')
>>> 'abcdc'
一些更普遍的例子:
replacesuffix('whatever-qweqweqwe','qwe','N',2)
>>> 'whatever-qweNN'
replacesuffix('whatever-qweqweqwe','qwe','N',-1)
>>> 'whatever-NNN'
replacesuffix('12.53000','0',' ',-1)
>>> '12.53 '
如果你只想剥离扩展:
'.'.join('abcdc.com'.split('.')[:-1])
# 'abcdc'
它适用于任何扩展名,与潜在的其他点存在的文件名以及。它只是将字符串拆分为一个点列表,并在没有最后一个元素的情况下将其连接起来。
url[:-4]怎么样?