如何从python中的url中删除.com?

时间:2016-07-29 11:48:56

标签: python urlparse

我想删除网址中的域名 对于例如用户输入了www.google.com 但我只需要www.google

如何在python中执行此操作? 谢谢

4 个答案:

答案 0 :(得分:3)

这是一个非常普遍的问题。但最简单的答案如下(假设url持有有问题的URL):

if url.endswith(".com"):
    url = url[:-4]

如果你想删除最后一个句号及其右边的所有内容,代码会更复杂一些:

pos = url.rfind('.') # find rightmost dot
if pos >= 0:         # found one
    url = url[:pos]

答案 1 :(得分:2)

要解决此问题而不必处理域名问题,您可以从左侧查找点并在第二个点处停止。

t = 'www.google.com'
a = t.split('.')[1]
pos = t.find(a)
t = t[:pos+len(a)]

>>> 'www.google'

答案 2 :(得分:0)

如果你想在最后删除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')

答案 3 :(得分:-1)

这里需要的是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与此相反。检查这些docs。 另请检查striplstrip函数。

更新

由于@SteveJessop指出上面的示例不是正确的解决方案所以我提交了另一个解决方案,虽然它与此处的另一个答案相关,但它会先检查字符串是否以'.com' 之间。

url = 'www.foo.com'
if url.endswith('.com'):
    url = url[:-4]
    print (url)