简体   繁体   English

Python打印string.split不带方括号

[英]Python printing string.split without square braces

I have 我有

cmd=arg[3:]

which gives for eg 这给例如

['file python parameter1=5 parameter2=456 ']

When I am printing I want to print in the format - python file parameters.. 当我打印时,我想以以下格式打印-python文件参数。

I tried 我试过了

print "%s %s %s" % (string.split(cmd[0])[1],string.split(cmd[0])[0],string.split(cmd[0])[2:])

which gives 这使

python file ['parameter1=5 parameter2=456 '] python文件['parameter1 = 5 parameter2 = 456']

How can i get the parameters part printed without the square braces or the quotes? 我如何才能在没有方括号或引号的情况下打印参数部分?

Thanks. 谢谢。 For the last part how can I print 最后一部分我该如何打印

You are asking Python to turn a list into a string. 您正在要求Python将列表转换为字符串。 This is why you are seeing the brackets and quotes. 这就是为什么您会看到方括号和引号。 All you need to do is use join to make it a string again. 您需要做的就是使用join再次使其成为字符串。

" ".join(string.split(cmd[0])[2:])

or if you really prefer the string module 或者如果您真的更喜欢字符串模块

string.join(" ", string.split(cmd[0])[2:])

I would prefer to see the code written like this if I were doing a code review: 如果要进行代码审查,我希望看到这样编写的代码:

fname, interp, args = cmd[0].split(" ", 2)
print "%s %s %s" % (interp, fname, args)

You could try something like that: 您可以尝试这样的事情:

' '.join(cmd[0].split()[2:])

instead of: 代替:

string.split(cmd[0])[2:]

Also, I would recommend you to use an intermediate variable to avoid to do the same split 3 times... Or even better : 另外,我建议您使用中间变量来避免进行3次相同的分割...甚至更好:

print ' '.join(cmd[0].split(' ', 2))

or actually simply: 或者实际上只是:

print cmd[0]

But I guess you don't want to only print it... 但是我想你不想只打印它...

% -style字符串格式相比,优先使用format方法。

print "{0[1]} {0[0]} {0[2]}".format(cmd[0].split(None, 2)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM