William February 2016

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?

Answers


Matthew February 2016

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.


jxmorris12 February 2016

Use the split() method to break up a string by one character.

fullstr.split('|') == ['my', 'name', 'is', 'will']

And then what you want is here:

fullstr.split('|')[1] == 'name'


minitoto February 2016

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]

Post Status

Asked in February 2016
Viewed 1,043 times
Voted 7
Answered 3 times

Search




Leave an answer