如何'\id '在字符串后面抓住第一个单词?
串:
'\id hello some random text that can be anything'
Run Code Online (Sandbox Code Playgroud)
蟒蛇
for line in lines_in:
if line.startswith('\id '):
book = line.replace('\id ', '').lower().rstrip()
Run Code Online (Sandbox Code Playgroud)
我得到了什么
book = 'hello some random text that can be anything'
Run Code Online (Sandbox Code Playgroud)
我想要的是
book = 'hello'
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 11
一种选择:
words = line.split()
try:
word = words[words.index("\id") + 1]
except ValueError:
pass # no whitespace-delimited "\id" in the string
except IndexError:
pass # "\id" at the end of the string
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 10
>>> import re
>>> text = '\id hello some random text that can be anything'
>>> match = re.search(r'\\id (\w+)', text)
>>> if match:
print match.group(1)
Run Code Online (Sandbox Code Playgroud)
一个更完整的版本,可以捕获任何空格 '\id'
re.search(r'\\id\s*(\w+)', text)
Run Code Online (Sandbox Code Playgroud)