![](/img/trans.png)
[英]Python printing the first item of each nested list with a single print command
[英]Python: Print first two characters of each item in a list. (without spaces)
到目前为止的代码:
fullname = "John Doe"
namelist = fullname.split()
for word in namelist:
print word[:2].lower(),
输出:
jo do
我希望它输出:
jodo
任何和所有建议,欢迎:)
逗号创建一个空格。 尝试创建列表理解并将其与空字符串连接:
>>> print "".join(word[:2].lower() for word in namelist)
jodo
要以较小的步骤查看它如何工作:
>>> firsts = [word[:2].lower() for word in namelist]
>>> firsts
['jo', 'do']
>>> print "".join(firsts)
jodo
print
“魔术逗号”总是插入空格,因此您不能以这种方式进行操作。
您有三种选择:
print ''.join(word[:2].lower() for word in namelist)
。 stdout
而不是使用print
: sys.stdout.write(word[:2].lower())
print
,它可以通过这种方式进行操作。 首先, from __future__ import print_function
代码顶部的from __future__ import print_function
。 然后, print(word[:2].lower(), end='')
。 >>> fullname = "John Doe"
>>> words = fullname.lower().split()
>>> words
['john', 'doe']
>>> print("".join(x[:2] for x in words))
jodo
[:2]选择第一个2个字母。 lower
将它们转换为小写。使用+
可以连接字符串。
python 2.x:
>>> print "".join(x[:2] for x in words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.