我有以下代码:
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中工作?对于第一次尝试的具体解释。
当前回答
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'
其他回答
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'
对于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”)
这也可以与str.endswith(后缀)相结合,如果你只需要分割“。com”,或任何特定的东西。
在我的情况下,我需要引发一个异常,所以我做了:
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)]
因为似乎还没有人指出这一点:
url = "www.example.com"
new_url = url[:url.rfind(".")]
这应该比使用split()的方法更有效,因为不会创建新的列表对象,而且这种解决方案适用于带有几个点的字符串。
这是正则表达式的完美用法:
>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'