繁体   English   中英

在两点之间找到字符串的最佳方法

[英]Best way to find strings between two points

我知道这是相当基本的,但我想知道在两个引用点之间找到字符串的最佳方法是什么。

例如:

在两个逗号之间找到字符串:

Hello, This is the string I want, blabla

我最初的想法是创建一个列表并让它做这样的事情:

stringtext= []
commacount = 0
word=""
for i in "Hello, This is the string I want, blabla":
    if i == "," and commacount != 1:
        commacount = 1
    elif i == "," and commacount == 1:
        commacount = 0
    if commacount == 1:
        stringtext.append(i)

print stringtext
for e in stringtext:
    word += str(e)

print word

然而,我想知道是否有一种更简单的方法,或者可能只是一种简单的方式。 谢谢!

这就是str.split(delimiter)的用途。
它返回一个列表,您可以执行[1]或迭代。

>>> foo = "Hello, this is the string I want, blabla"
>>> foo.split(',')
['Hello', ' this is the string I want', ' blabla']
>>> foo.split(',')[1]
' this is the string I want'

如果你想摆脱领先的空间你可以使用str.lstrip()str.strip()来删除尾随:

>>> foo.split(',')[1].lstrip()
'this is the string I want'

通常有一种内置方法可用于Python中的简单方法:-)
有关更多信息,请查看内置类型 - 字符串方法

另一种选择是在这些引用不需要相同时(如两个逗号中)找到两个引用的索引:

a = "Hello, This is the string I want, blabla"
i = a.find(",") + 1
j = a.find(",",i)
a[i:j]
>>> ' This is the string I want'

如果你希望开始/结束点不同,或者你想要更复杂的标准,我会使用re - 这会更容易。

例:

>>> import re
>>> s = "Hello, This is the string I want, blabla"
>>> re.search(',(.*?),', s).group(1)
' This is the string I want'

暂无
暂无

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

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