我想删除 url 中的域 例如用户输入 www.google.com 但我只需要 www.google
如何在python中做到这一点?谢谢
这是一个非常普遍的问题。但最窄的答案如下(假设url
持有有问题的 URL):
if url.endswith(".com"):
url = url[:-4]
如果要删除最后一个句点及其右侧的所有内容,则代码会稍微复杂一些:
pos = url.rfind('.') # find rightmost dot
if pos >= 0: # found one
url = url[:pos]
为了解决这个问题而不涉及处理域名的问题,您可以从左侧查找点并在第二个点处停止。
t = 'www.google.com'
a = t.split('.')[1]
pos = t.find(a)
t = t[:pos+len(a)]
>>> 'www.google'
如果要在末尾删除 4 个字符,请将其切片
url = 'www.google.com'
cut_url = str[:-4]
# output : 'www.google'
更高级的答案
如果您有所有可能域的列表domains
:
domains = ['com', 'uk', 'fr', 'net', 'co', 'nz'] # and so on...
while True:
domain = url.split('.')[-1]
if domain in domains:
url = '.'.join(url.split('.')[:-1])
else:
break
或者,例如,如果您有一个没有分隔的域.co
列表.uk
:
domains = ['.com', '.co.uk', '.fr', '.net', '.co.nz'] # and so on...
for domain in domains:
if url.endswith(domain):
cut_url = url[:-len(domain)]
break
else: # there is no indentation mistake here.
# else after for will be executed if for did not break
print('no known domain found')
你在这里需要的是rstrip
功能。
试试这个代码:
url = 'www.google.com'
url2 = 'www.google'
new_url = url.rstrip('.com')
print (new_url)
new_url2 = url2.rstrip('.com')
print (new_url2)
rstrip
仅当字符串存在时才会剥离,在本例中为“.com”。如果没有,它就会离开它。rstrip
用于剥离“最右边”匹配的字符串,与lstrip
此相反。检查这些文档。还要检查strip和lstrip函数。
正如@SteveJessop 指出的那样,上面的示例不是正确的解决方案,所以我提交了另一个解决方案,虽然它与此处的另一个答案有关,但它确实首先检查字符串是否以“.com”结尾。
url = 'www.foo.com'
if url.endswith('.com'):
url = url[:-4]
print (url)