Skip to main content
 首页 » 编程设计

Python 2.7 打印字符串

2025年05月04日20qlqwjy

我想用下面的例子打印所有的名字。名称每次都是随机的。

txt = "[something name=\"Paul\" other=\"1/1/1\"][something name=\"James\" other=\"4/3/5\"][something name=\"Victor\" other=\"7/2/6\"][something name=\"Jane\" other=\"4/3/6\"]" 

我知道如何打印第一个名字:

print str(txt[txt.index('[something name=\"')+17:txt.index(' other')-1]) 

但是我怎样才能全部打印出来呢?我需要在新行中打印所有名称:

Paul 
James 
Victor 
Jane 

请您参考如下方法:

看起来你可以在这里使用正则表达式:

import re 
txt = "[something name=\"Paul\" other=\"1/1/1\"][something name=\"James\" other=\"4/3/5\"][something name=\"Victor\" other=\"7/2/6\"][something name=\"Jane\" other=\"4/3/6\"]" 
for name in re.findall('name\=\\"(.*?)\\\"', txt): 
    print name 

打印:

Paul 
James 
Victor 
Jane