url = 'abcdc.com'
print(url.strip('.com'))
我预期的是:
abcdc
我得到的是:abcd
现在我要做的是url.rsplit('.com', 1)
有更好的方法吗?
请参阅如何在Python中使用.strip/.rstrip/.lstrip字符串方法?以获得有关第一次尝试的具体解释。
url = 'abcdc.com'
print(url.strip('.com'))
abcdc
我得到的是:abcd
现在我要做的是url.rsplit('.com', 1)
有更好的方法吗?
对于URL(由于给定的示例似乎是该主题的一部分),可以这样做:
import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)
#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)
两者的输出结果都为:('http://www.stackoverflow', '.com')
如果你只想要分割".com"或其他特定字符串,也可以与str.endswith(suffix)
结合使用。
假设您想删除域名,无论是什么 (.com, .net, 等等)。我建议找到 .
并删除从该点开始的所有内容。
url = 'abcdc.com'
dot_index = url.rfind('.')
url = url[:dot_index]
在这里,我使用rfind
来解决像abcdc.com.net
这样的URL问题,该问题应缩短为名称abcdc.com
。
如果您也关注www.
,则应明确检查它们:
if url.startswith("www."):
url = url.replace("www.","", 1)
replace函数中的1是用于处理奇怪的边界情况,比如www.net.www.com
如果你的url更加复杂,请查看其他人提供的正则表达式答案。
如果你只是想剥离文件扩展名:
'.'.join('abcdc.com'.split('.')[:-1])
# 'abcdc'
因为这是一个非常流行的问题,我添加了另一个现在可用的解决方案。使用Python 3.9 (https://docs.python.org/3.9/whatsnew/3.9.html),将添加函数removesuffix()
(和removeprefix()
),这个函数正是在这里所询问的。
url = 'abcdc.com'
print(url.removesuffix('.com'))
输出:
'abcdc'
PEP 616 (https://www.python.org/dev/peps/pep-0616/) 显示了它的行为方式(这不是真正的实现):
def removeprefix(self: str, prefix: str, /) -> str:
if self.startswith(prefix):
return self[len(prefix):]
else:
return self[:]
并且它相对于自行实现的解决方案具有以下好处:
更加稳定: 代码不会依赖于用户计算文字长度。
更高效: 代码无需调用Python内置的len函数或更昂贵的str.replace()方法。
更具描述性: 这些方法提供了更高级别的API,有助于提高代码可读性,而不是传统的字符串切片方法。
def remove_suffix(v, s):
return v[:-len(s)] if v.endswith(s) else v
remove_suffix("abc.com", ".com") == 'abc'
remove_suffix("abc", ".com") == 'abc'
对于一个正则表达式:
def remove_suffix_compile(suffix_pattern):
r = re.compile(f"(.*?)({suffix_pattern})?$")
return lambda v: r.match(v)[1]
remove_domain = remove_suffix_compile(r"\.[a-zA-Z0-9]{3,}")
remove_domain("abc.com") == "abc"
remove_domain("sub.abc.net") == "sub.abc"
remove_domain("abc.") == "abc."
remove_domain("abc") == "abc"
对于一组常量后缀,大量调用的渐近最快方法:
def remove_suffix_preprocess(*suffixes):
suffixes = set(suffixes)
try:
suffixes.remove('')
except KeyError:
pass
def helper(suffixes, pos):
if len(suffixes) == 1:
suf = suffixes[0]
l = -len(suf)
ls = slice(0, l)
return lambda v: v[ls] if v.endswith(suf) else v
si = iter(suffixes)
ml = len(next(si))
exact = False
for suf in si:
l = len(suf)
if -l == pos:
exact = True
else:
ml = min(len(suf), ml)
ml = -ml
suffix_dict = {}
for suf in suffixes:
sub = suf[ml:pos]
if sub in suffix_dict:
suffix_dict[sub].append(suf)
else:
suffix_dict[sub] = [suf]
if exact:
del suffix_dict['']
for key in suffix_dict:
suffix_dict[key] = helper([s[:pos] for s in suffix_dict[key]], None)
return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v[:pos])
else:
for key in suffix_dict:
suffix_dict[key] = helper(suffix_dict[key], ml)
return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v)
return helper(tuple(suffixes), None)
domain_remove = remove_suffix_preprocess(".com", ".net", ".edu", ".uk", '.tv', '.co.uk', '.org.uk')
import re
def rm_suffix(url = 'abcdc.com', suffix='\.com'):
return(re.sub(suffix+'$', '', url))
我希望以最能表达的方式重申这个答案。当然,以下方法会占用更少的CPU时间:
def rm_dotcom(url = 'abcdc.com'):
return(url[:-4] if url.endswith('.com') else url)
然而,如果CPU是瓶颈,为什么要用Python编写代码呢?
那么什么情况下CPU会成为瓶颈呢?也许在驱动程序中。
使用正则表达式的优点是代码可重用性。如果您想要删除仅有三个字符的“.me”呢?同样的代码就可以解决问题:
代码如下:
>>> rm_sub('abcdc.me','.me')
'abcdc'
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)]
'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'
a = 'www.computerbugs.com'
时,结果为 'www'
。 - yairchu'www.computerbugs.com'[::-1].split('.com'[::-1], 1)[-1][::-1]
- Ben Farmer'www.computerbugs.com'.rsplit('.com', 1)[0]
- Ben Farmer更广泛的解决方案,增加了“替换后缀”(可以通过替换为空字符串来移除)和“设置最大替换次数”的可能性:
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 '
在Python 3.8中移除后缀的函数:
def removesuffix(text, suffix):
if text.endswith(suffix):
return text[:-len(suffix)]
else:
return text