Python Forum

Full Version: Print characters in a single line rather than one at a time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
 
for x in range(len(s)):
    if x % 2!=0:
        print(s[x])
This is the code I am using to print every other character in a string. However, when I run it, it prints the characters like this:
a
b
c
d
How can I get it to print them in a single line?(ex. abcd)
You can tell print not to insert a newline:
print(s[x], end="")
But my preference would be to join() the bits together before printing.

>>> s = "abcdefg"
>>> print("".join(char for index, char in enumerate(s) if index % 2 != 0))
bdf
>>> print(s[1::2])  #Or to do it directly
bdf