Python Forum
Print characters in a single line rather than one at a time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Print characters in a single line rather than one at a time
#1
 
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)
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read characters of line and return positions Gizzmo28 2 142 Nov-04-2020, 09:27 AM
Last Post: perfringo
  print a line break in writelines() method leodavinci1990 1 183 Oct-12-2020, 06:36 AM
Last Post: DeaD_EyE
  How to print n days back date at give time Mekala 1 126 Oct-10-2020, 03:35 AM
Last Post: bowlofred
  get two characters, count and print from a .txt file Pleiades 9 399 Oct-05-2020, 09:22 AM
Last Post: perfringo
  How to print string multiple times on new line ace19887 7 270 Sep-30-2020, 02:53 PM
Last Post: buran
  Using lambdas and map() to parse substrings in a single line Drone4four 5 598 Sep-20-2020, 10:38 AM
Last Post: snippsat
  Having a hard time conceptualizing how to print something MysticLord 6 413 Sep-19-2020, 10:43 PM
Last Post: MysticLord
  Pattern Require Last Line Print() why? Harshil 4 319 Aug-08-2020, 04:54 PM
Last Post: Harshil
  Print a certain string only the first time it appears in a test file buttercup 5 384 Jul-23-2020, 01:30 PM
Last Post: palladium
  Print output in single file using pramika loop deepakkhw 1 340 Jul-11-2020, 11:57 AM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020