0

I want to write a program that prints a word 3 times. The first two iterations should have a space after them, but the 3rd line shouldn't.

Example of desired output: https://i.stack.imgur.com/XXEGD.jpg

This is the code I'm trying:

n = input("Enter a word: ")
  for x in range(len(n)):
  print((n[x]+" ")*3)
  n.rstrip()

This is the output I'm getting - rstrip() doesn't seem to be working.

https://i.stack.imgur.com/GGL57.jpg

Any suggestions on how to fix this?

brigfalk
  • 13
  • 4
  • format your code – RomanPerekhrest Sep 20 '19 at 18:07
  • First, you need to format your code the way you have it. It is not clear. Second, you are doing rstrip on the whole string, but you are printing individual characters. And Third, you are adding the spaces yourself with `n[x]+" "` – Mad Wombat Sep 20 '19 at 18:08
  • Also, you're doing nothing that would change behavior for the 3rd time. You're printing before you ever do `n.rstrip()` so you can't expect your print output to have changed based on it. – MyNameIsCaleb Sep 20 '19 at 18:09
  • @MadWombat sorry, I am new to python. what do you mean by "format your code?" – brigfalk Sep 20 '19 at 18:13
  • The code in your question is not indented properly. – Mad Wombat Sep 20 '19 at 18:14
  • Another tip, seeing that you are a beginner: don't give "random" names to your variables like x, n, and so on. Python is the ultimately readable programming code. Reflect that in your variable and function names. E.g. `word = input(); for char_id in range()` and so on. – Bram Vanroy Sep 20 '19 at 18:16

2 Answers2

1

You need to rstrip() before you print and you need to rstrip() what you are actually printing, not the whole line. This would work

n = input("Enter a word: ")
for x in range(len(n)):
    s = (n[x] + " ") * 3
    print(s.rstrip())

A better way would be to use join()

n = input("Enter a word: ")
for x in range(len(n)):
    print(" ".join(n[x] * 3))

And you can iterate over string directly, so this would also work

n = input("Enter a word: ")
for x in n:
    print(" ".join(x * 3))

Or you could get clever and do something like this

n = input("Enter a word: ")
list(map(print, [" ".join(i * 3) for i in n]))
Mad Wombat
  • 14,490
  • 14
  • 73
  • 109
  • See my updated answer and accept it if this answers your question – Mad Wombat Sep 20 '19 at 18:18
  • `list(map(print, ...)` is generally an anti-pattern. You could potentially be creating an extremely large list filled with `None`, which is rather expensive. See https://stackoverflow.com/q/5753597/ It discusses list comprehensions instead of `list(map())`, but the arguments there can also be applied here. – iz_ Sep 20 '19 at 18:23
  • @iz_ agreed, just wanted to get a bit funky – Mad Wombat Sep 20 '19 at 18:27
0

You almost had it. You're calling rstrip() after the print line which has no impact since it's already been printed.

n = input("Enter a word: ")
for x in range(len(n)):
    print((n[x]+" ")*2 + n[x])
k-war
  • 540
  • 3
  • 15