python 查找字符第一次出现位置_Python查找字符串列表在字符串中第一次出现的索引位置...

按照示例的逻辑,这是找到“第一个”匹配箭头并打印其位置的最方便方法。但是,集合的顺序不是先进先出,所以如果你想保持顺序,我建议用列表代替集合来代替箭头列表,这样可以保持顺序。在arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}

def cxn(line, arrowlist):

try:

result = tuple((x, line.find(x)) for x in arrowlist if x in line)[0]

print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))

# Remember in general it's not a great idea to use an exception as

# broad as Exception, this is just for example purposes.

except Exception:

return 0

如果要在提供的字符串(行)中查找第一个匹配项,可以这样做:

^{pr2}$

或者,如果您可以访问标准库,则可以使用运算符.itemgetter为了达到几乎相同的效果并从较少的函数调用中获得效率:from operator import itemgetter

arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}

def cxn(line, arrowlist):

try:

# key first sorts on the position in string then alphanumerically

# on the arrow match (i.e. -> and ->x matched in same position

# will return -> because when sorted alphanumerically it is first)

result = sorted([(x, line.find(x)) for x in arrowlist if x in line], key=(itemgetter(1,0)))[0]

print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))

except Exception:

return 0

***注意:我使用的箭头列表与您的示例稍有不同,只是因为您提供的箭头列表似乎弄乱了默认代码格式(可能是因为引号结束问题)。记住,您可以像这样在字符串前面加上“r”:r"Text that can use special symbols like the escape \and\ be read in as a 'raw' string literal\"。See this question获取有关原始字符串文本的详细信息。在

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值