首页 > 解决方案 > Python:3 - 在找到关键字后将字符串设为变量?

问题描述

如果我不知道单词是什么,我正在尝试找到一种优雅(简单)的方法来将字符串中的子字符串保存为变量,但我确实知道它之前的四个单词是什么。

如果字符串是(“重置 johnny.mnemonic 的密码”),我需要能够在找到子字符串后存储字符串 johnny.mnemonic?但是怎么做?

string = " will you reset password for johnny.mnemonic please"
substring = "reset password for"


if string.find(substring) is not -1:
    print("i found the substring to request password reset")
    #now add the next sub-string to as a variable here, user should be be next string over
else:
    print("sorry, no request found.")

标签: python-3.xinputsubstring

解决方案


也许这是适合您情况的解决方案:

cstring = " will you reset password for johnny.mnemonic please"
substring = "reset password for"

if substring in cstring:
    words = cstring.split()
    person = words[words.index('for')+1]
else:
    person = False

if person:
    #do stuff

推荐阅读