简体   繁体   English

在Python中获取子串

[英]Getting Substring in Python

I have a string fullstr = "my|name|is|will" , and i would like to extract the substring "name". 我有一个字符串fullstr = "my|name|is|will" ,我想提取子字符串“name”。 I used string.find to find the first position of '|' 我使用string.find找到'|'的第一个位置 like this: 像这样:

pos = fullstr.find('|') 

and it return 2 as the first position of '|' 它返回2作为'|'的第一个位置 . I want to print substring from pos position until next '|'. 我想从pos位置打印子串直到下一个'|'。 There's rsplit feature, but it return the very first char from right of string, since there're many '|' rsplit功能,但它返回字符串右边的第一个字符,因为有很多'|' 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. 抓取第二个项目(列表为0索引,因此这是索引1)将返回所需的结果。

You can still use find if you want, find first position of | 你仍然可以使用find ,找到|第一个位置 and next one: 和下一个:

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

Similar way using index : 使用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: 在您的字符串中使用re.finditer并按索引切片:

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 : 您还可以查看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 : 使用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 : 而最简单的方法就是使用splitrsplit

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

Use the split() method to break up a string by one character. 使用split()方法将字符串分解为一个字符。

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

And then what you want is here: 然后你想要的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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