0

I have a program that takes a string input, and an integer input. The integer determines 2 things, how many times the string is printed, and which character in the string is visible, otherwise replaced by "."

For example - String: Hello World Integer: 3

Should show as:

H..l..W..l.
.e..o..o..d
..l.. ..r..

Basically printing diagonal text.

How would I go about having every 3rd character in the string shown, otherwise replaced by "."? Regardless of the inputted string and beginning with the first.

I only need the function, I got the rest of the code.

The code so far to is this (not compact):

stringVar = input("String: ")
countVar = input("Count: ")

countInt = int(countVar)
stringInt = len(stringVar)

if countInt > stringInt:
    print("Number should be between 1 and the lenght of the string!")
    exit()

if countInt < 1:
    print("Number should be between 1 and the lenght of the string!")
    exit()

count = 1        

while count <= countInt:
    print(stringVar)
    count = count + 1

I just need a way to also replace the characters in StringVar.

6
  • Can you show us what you have tried so far? Commented Feb 12, 2014 at 22:22
  • Have you made any attempt to write this yourself? If so, can you provide the code? Commented Feb 12, 2014 at 22:22
  • Just added the code so far. Commented Feb 12, 2014 at 22:27
  • 2
    This reads like homework. Beware, if you take the one line answers below, your teacher will immediately know you didn't do this yourself. Commented Feb 12, 2014 at 22:33
  • 2
    That is precisely why I made my answer one line. Commented Feb 12, 2014 at 22:42

2 Answers 2

2
>>> n = 3
>>> message = 'Hello World'
>>> print ('\n'.join([''.join(['.' if (j-i) % n else c for j, c in enumerate('hello world')]) for i in range(n)]))
h..l..w..l.
.e..o..o..d
..l.. ..r..

The magic happens in (j-i) % n. Modulus is positive if not divisible by n. Beyond that there are two list comprehensions, outer for each line, inner for each character

Sign up to request clarification or add additional context in comments.

Comments

2
s = 'Hello World!!!'
n = 3
rep = '.'

for j in range(n):
    print(''.join([v if (i - j)%n == 0 else rep for i, v in enumerate(s)]))

# H..l..W..l..!.
# .e..o..o..d..!
# ..l.. ..r..!..

The code iterates over the required number of lines (0,1,2 for n=3). The ''.join(...) method checks if (i - j)%n == 0 to decide when to print the letter, otherwise prints the rep string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.