3

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?

1
  • 1
    if you want to split the input on "|", then simply use sullstr.split("|"), which would result in ["my", "name", "is", "will"] Commented Feb 8, 2016 at 6:31

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.