我有以下代码:
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中工作?对于第一次尝试的具体解释。
当前回答
如果你只想剥离扩展:
'.'.join('abcdc.com'.split('.')[:-1])
# 'abcdc'
它适用于任何扩展名,与潜在的其他点存在的文件名以及。它只是将字符串拆分为一个点列表,并在没有最后一个元素的情况下将其连接起来。
其他回答
假设你想删除域名,不管它是什么(.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比这更乱,看看人们用正则表达式回答的问题。
在我的情况下,我需要引发一个异常,所以我做了:
class UnableToStripEnd(Exception):
"""A Exception type to indicate that the suffix cannot be removed from the text."""
@staticmethod
def get_exception(text, suffix):
return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
.format(suffix, text))
def strip_end(text, suffix):
"""Removes the end of a string. Otherwise fails."""
if not text.endswith(suffix):
raise UnableToStripEnd.get_exception(text, suffix)
return text[:len(text)-len(suffix)]
def strip_end(text, suffix):
if suffix and text.endswith(suffix):
return text[:-len(suffix)]
return text
这是正则表达式的完美用法:
>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'
这个方法有一个严重的缺陷,分区没有锚定到url的末尾,可能会返回虚假的结果。例如,URL“www.comcast.net”的结果是“www”(不正确),而不是预期的“www.comcast.net”。因此,这种解决方案是邪恶的。除非你知道你在做什么,否则不要使用它!
url.rpartition('.com')[0]
这是相当容易键入的,也正确地返回原始字符串(没有错误)时,后缀'.com'从url中丢失。