gpt4 book ai didi

python - 打印关键字后的 5 个字符

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:10 25 4
gpt4 key购买 nike

我想制作一个简单的代码,它接受一段文本,扫描关键字并打印关键字以及接下来的 5 个字符。请注意,关键字可以在文本中出现多次。

  string = 'my name is luka 90/91, I live on the second floor'
keyword = 'luka'

if key in string:
print (key + key[0:5])

输出应该是 luka 90\91

最佳答案

使用 str.find ,可以得到匹配字符串的索引:

>>> string = 'my name is luka 90/91, I live on the second floor'
>>> keyword = 'luka'
>>> string.find(keyword)
11

>>> i = string.find(keyword)
>>> string[i:i+len(keyword)+5]
'luka 90/9'
>>> string[i:i+len(keyword)+5+1] # +1 (count space in between)
'luka 90/91'

更新 要获取所有出现的地方,您需要在循环中找到子字符串。

string = 'my name is luka 90/91, I live on the second floor luka 12345'
keyword = 'luka'

i = 0
while True:
i = string.find(keyword, i) # `i` define from where the find start.
if i < 0:
break
j = i + len(keyword) + 5 + 1
print(string[i:j])
i = j

更新 使用 re.findall 的解决方案:

>>> string = 'my name is luka 90/91, I live on the second floor luka 12345'
>>> keyword = 'luka'
>>> import re
>>> re.findall(re.escape(keyword) + '.{5}', string)
['luka 90/9', 'luka 1234']
>>> re.findall(re.escape(keyword) + '.{6}', string)
['luka 90/91', 'luka 12345']
  • luka 字面匹配。 .{5} 匹配后面的任意 5 个字符。
  • 如果您想要匹配少于 5 个字符的字符。请改用 .{1,5}
  • re.escape luka 不需要。如果在正则表达式中有特殊含义的特殊字符,则需要填写。

关于python - 打印关键字后的 5 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42328840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com