简体   繁体   中英

Python: Print first two characters of each item in a list. (without spaces)

Code so far:

fullname = "John Doe"
namelist = fullname.split()
for word in namelist:
    print word[:2].lower(),

This outputs:

jo do

I want it to output:

jodo

Any and all suggestions welcomed :)

The comma creates a space. Try creating a list comprehension and joining it with empty string:

>>> print "".join(word[:2].lower() for word in namelist)
jodo

To see how it's working in smaller steps:

>>> firsts = [word[:2].lower() for word in namelist]
>>> firsts
['jo', 'do']
>>> print "".join(firsts)
jodo

The print "magic comma" always inserts spaces, so you can't do things this way.

You have three choices:

  1. Join the words up into a string first, then print that string: print ''.join(word[:2].lower() for word in namelist) .
  2. Write directly to stdout instead of using print : sys.stdout.write(word[:2].lower())
  3. Use Python 3-style print , which can do things this way. First, from __future__ import print_function at the top of your code. Then, 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] selects 1st two letter . lower converts them to lowercase.using + you can concatenate string.

python 2.x:

>>> print "".join(x[:2] for x in words)

The print function from Python 3 has a parameter sep (for "separator") which can be set to a null string. Using that and using the * operator to specify passing in a variable number of arguments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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