简体   繁体   中英

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?

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.

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]

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM