【问题标题】:Python: 3 - make string after found keywords a variable?Python:3 - 在找到关键字后将字符串设为变量?
【发布时间】:2018-10-18 12:22:00
【问题描述】:

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

如果字符串是(“重置 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.x input substring


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    input_string = " will you reset password for johnny.mnemonic please"
    substring = "reset password for " # keep in mind the ending space
    first_index = input_string.find(substring)
    if first_index != -1: # if found
        last_index = first_index + len(substring)
        print(input_string[last_index:].split(" ")[0]) # split into words and get the first word
    

    输出:

    johnny.mnemonic
    

    基本上它会搜索“reset password for”,然后获取子字符串后面的下一个单词

    【讨论】:

      【解决方案3】:

      我假设您想要存储有关某个人的信息并使用该人的姓名检索此信息。 我建议使用这样的字典:

      s = 'reset the password for johnny.mnemonic'
      t = 'create the password for another.guy'
      u = 'tell the password for a.gal'
      
      d = {}
      d[s.split()[-1]] = s
      d[t.split()[-1]] = t
      d[u.split()[-1]] = u
      
      
      for k, v in d.items():
          print(k, '\n\t', v)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-29
        • 1970-01-01
        • 2016-10-11
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多