Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Chars in Python

Tags:

python

does anybody know how to delete all characters behind a specific character??

like this:

http://google.com/translate_t

into

http://google.com
like image 472
WoW Avatar asked Jul 12 '26 04:07

WoW


2 Answers

if you're asking about an abstract string and not url you could go with:

>>> astring ="http://google.com/translate_t"
>>> astring.rpartition('/')[0]
http://google.com
like image 163
SilentGhost Avatar answered Jul 13 '26 19:07

SilentGhost


For urls, using 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'

For arbitrary strings, using re:

>>> import re
>>> re.split(r'\b/\b', 'http://google.com/path/to/resource', 1)
['http://google.com', 'path/to/resource']
like image 39
Constantin Avatar answered Jul 13 '26 18:07

Constantin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!