打印关键字后面的5个字符

Mr.*_*ply 3 python string

我想创建一个简单的代码,它接受一个文本,扫描关键字并打印关键字以及接下来的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])
Run Code Online (Sandbox Code Playgroud)

输出应该是luka 90\91

fal*_*tru 5

使用str.find,您可以获取匹配字符串的索引:

>>> string = 'my name is luka 90/91, I live on the second floor'
>>> keyword = 'luka'
>>> string.find(keyword)
11
Run Code Online (Sandbox Code Playgroud)
>>> 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'
Run Code Online (Sandbox Code Playgroud)

更新要获取所有实例,您需要在循环中查找子字符串.

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
Run Code Online (Sandbox Code Playgroud)

UPDATE解决方案使用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']
Run Code Online (Sandbox Code Playgroud)
  • luka从字面上看..{5}匹配以下任何5个字符.
  • 如果你想匹配字符,即使它们少于5个字符.请.{1,5}改用.
  • re.escape没有必要luka.如果特殊字符在正则表达式中具有特殊含义,则需要它.