删除Python中的Chars

WoW*_*WoW 2 python text-processing

有谁知道如何删除特定字符后面的所有字符?

像这样:

http://google.com/translate_t
Run Code Online (Sandbox Code Playgroud)

http://google.com
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 6

如果你问的是一个抽象的字符串,而不是你可以使用的url:

>>> astring ="http://google.com/translate_t"
>>> astring.rpartition('/')[0]
http://google.com
Run Code Online (Sandbox Code Playgroud)


Con*_*tin 5

对于网址,使用urlparse:

>>> import urlparse
>>> parts = urlparse.urlsplit('http://google.com/path/to/resource?query=spam#anchor')
>>> parts
('http', 'google.com', '/path/to/resource', 'query=spam', 'anchor')
>>> urlparse.urlunsplit((parts[0], parts[1], '', '', ''))
'http://google.com'
Run Code Online (Sandbox Code Playgroud)

对于任意字符串,使用re:

>>> import re
>>> re.split(r'\b/\b', 'http://google.com/path/to/resource', 1)
['http://google.com', 'path/to/resource']
Run Code Online (Sandbox Code Playgroud)