Skip to main content
 首页 » 编程设计

python之抓取字符串中 '\id' 之后的第一个单词

2025年05月04日23haluo1

我如何获取字符串中 '\id ' 之后的第一个单词?

字符串:

'\id hello some random text that can be anything' 

python

for line in lines_in: 
    if line.startswith('\id '): 
        book = line.replace('\id ', '').lower().rstrip() 

我得到了什么

book = 'hello some random text that can be anything' 

我想要什么

book = 'hello' 

请您参考如下方法:

一个选项:

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