url1='www.google.com'
url2='http://www.google.com'
url3='http://google.com'
url4='www.google'
url5='http://www.google.com/images'
url6='https://www.youtube.com/watch?v=6RB89BOxaYY
Run Code Online (Sandbox Code Playgroud)
如何 从Python中删除http(s)和删除wwwURL?
Jan*_*ake 10
您可以使用 regex
url = 'http://www.google.com/images'
url = url.replace("http://www.","")
print url
Run Code Online (Sandbox Code Playgroud)
或者你可以使用 regular expressions
import re
url = re.compile(r"https?://(www\.)?")
url.sub('', 'http://www.google.com/images').strip().strip('/')
Run Code Online (Sandbox Code Playgroud)
一个更优雅的解决方案是使用 urlparse:
from urllib.parse import urlparse
def get_hostname(url, uri_type='both'):
"""Get the host name from the url"""
parsed_uri = urlparse(url)
if uri_type == 'both':
return '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
elif uri_type == 'netloc_only':
return '{uri.netloc}'.format(uri=parsed_uri)
Run Code Online (Sandbox Code Playgroud)
第一个选项包括https或http,具体取决于链接,第二部分netloc包括您要查找的内容。