Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Substring in Python

I have a string fullstr = "my|name|is|will" , and i would like to extract the substring "name". I used string.find to find the first position of '|' like this:

pos = fullstr.find('|') 

and it return 2 as the first position of '|' . I want to print substring from pos position until next '|'. There's rsplit feature, but it return the very first char from right of string, since there're many '|' in my string. How to print the substring?

like image 359
mfathirirhas Avatar asked Aug 06 '26 21:08

mfathirirhas


2 Answers

You can still use find if you want, find first position of | and 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 is to find all occurrences of | in your string using re.finditer and slice it by indexes:

import re

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

You can also take a look into re.search:

import re

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

There is an interesting way using enumerate:

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

And the easiest way just using split or rsplit:

fullstr = "my|name|is|will"
fullstr.split('|')[1]
fullstr.rsplit('|')[1]
like image 63
midori Avatar answered Aug 08 '26 11:08

midori


You can use

fullstr.split("|")[1]

which will break the string apart at the "|" marks and return a list. Grabbing the second item (lists are 0-indexed, so this is index 1) will return the desired result.

like image 25
Matthew Avatar answered Aug 08 '26 11:08

Matthew



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!