Getting Substring in Python -


i have string fullstr = "my|name|is|will" , , extract substring "name". used string.find find first position of '|' this:

pos = fullstr.find('|')  

and return 2 first position of '|' . want print substring pos position until next '|'. there's rsplit feature, return first char right of string, since there're many '|' in string. how print substring?

you can still use find if want, find first position of | , next one:

fullstr = "my|name|is|will" begin = fullstr.find('|')+1 end = fullstr.find('|', begin) print fullstr[begin:end] 

similar way using index:

fullstr = "my|name|is|will" begin = fullstr.index('|')+1 end = fullstr.index('|', begin) print fullstr[begin:end] 

another way find occurrences of | in string using re.finditer , slice indexes:

import re  = [sub.start() sub in re.finditer('\|', fullstr)] print fullstr[all[0]+1:all[1]]  

you can take re.search:

import re  fullstr = "my|name|is|will" print re.search(r'\|([a-z]+)\|', fullstr).group(1) 

there interesting way using enumerate:

fullstr = "my|name|is|will" = [p p, e in enumerate(fullstr) if e == '|'] print fullstr[all[0]+1:all[1]] 

and easiest way using split or rsplit:

fullstr = "my|name|is|will" fullstr.split('|')[1] fullstr.rsplit('|')[1] 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -