繁体   English   中英

Python:在列表中打印每个项目的前两个字符。 (无空格)

[英]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 “魔术逗号”总是插入空格,因此您不能以这种方式进行操作。

您有三种选择:

  1. 首先将单词连接成一个字符串,然后打印该字符串: print ''.join(word[:2].lower() for word in namelist)
  2. 直接写到 stdout而不是使用printsys.stdout.write(word[:2].lower())
  3. 使用Python 3样式的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)

Python 3中print函数具有一个参数sep (用于“分隔符”),可以将其设置为空字符串。 使用它并使用*运算符指定传递可变数量的参数:

from __future__ import print_function
fullname = "John Doe"
words = (word[:2].lower() for word in fullname.split())
print(*words, sep='')

暂无
暂无

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

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