python找到字符串中第一个汉字的位置_抓住在字符串中找到的列表中的第一个单词。 (Python)...

1586010002-jmsa.png

So, I have a list of words like so:

activationWords = ['cactus', 'cacti', 'rofl']

And I want to find any of those words and return the first word of any of those words appearing in a random string. I'll use this string as an example:

str = "Wow, rofl I found a cactus in a cacti pile."

As you can see with the above example string, the first instance of a word in the list is "rofl". I want to be able to detect that and return the word into a string that I can use to my discretion. How would I do this?

Keep in mind that that string is just an example. Each time I run this it will be using a different string.

解决方案

You can use str.find() here:

>>> activationWords = ['cactus', 'cacti', 'rofl']

>>> s = "Wow, rofl I found a cactus in a cacti pile."

>>> temp = [(s.find(i), i) for i in activationWords if i in s]

>>> print temp

[(20, 'cactus'), (32, 'cacti'), (5, 'rofl')]

>>> print min(temp)[1]

rofl

str.find() finds where the string is in the other string. It returns the index of the first letter.

[(s.find(i), i) for i in activationWords] is a list comprehension that returns a list of tuples, the first item being the result of str.find(), the second being the word.

Then we use min() here to get the lowest number, and [1] to get the word.

Note that you should not name a string str. It overrides the built-in type.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值