Skip to content Skip to sidebar Skip to footer

Delete Chars In Python

does anybody know how to delete all characters behind a specific character?? like this: http://google.com/translate_t into http://google.com

Solution 1:

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

Solution 2:

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']

Solution 3:

str="http://google.com/translate_t"
shortened=str[0:str.rfind("/")]

Should do it. str[a:b] returns a substring in python. And rfind is used to find the index of a character sequence, starting at the end of the string.


Post a Comment for "Delete Chars In Python"