python-3.x - 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.")
解决方案
也许这是适合您情况的解决方案:
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
推荐阅读
- h.264 - 通过 RTP 从 h264 比特流中识别帧类型
- dart - 在 Dart 中,我如何从 AST 到 Elements?
- android - 长按标签标题上的 Android TabLayout 烦人的弹出窗口(工具提示)
- javascript - 防止 EJS 文件被 Redis 缓存
- c# - 在 ASP.NET asmx webservice 中捕获 HTML 标记?
- java - 使用类和构造函数确定数组实现的输出
- rust - 无法理解 &mut &mut 参考
- python - 使用 Python 的 OpenVPN 连接 (Windows)
- algorithm - 在给定的两个时间段内可以完成的最大工作数 [双背包?]
- postgresql - 在postgres中计算连续天数