Home > front end >  Slicing a string based on user input printing the characters on each line
Slicing a string based on user input printing the characters on each line

Time:11-19

So basically, i need to get the user to input some type of string and then get the user to input a number and slice the string depending on the users number and print on a new line every time it sliced. I don't think that made since so here is an example

Welcome to the jungle.
5
Welco
me to
the
jungl
e.

I understand how to slice it but i dont understand how to get it to continue slicing until the full string is printed

y=input('enter a sentence ')
x=int(input('enter a number '))
z=0
while z==0:
 z==0
 print(y[0:x])
 print(y[x:]

CodePudding user response:

You can use the input string as the loop control variable. That is, keep looping while there is still something left in the input string. Here's a suggestion:

y=input('enter a sentence ')
x=int(input('enter a number '))
while len(y):
 print(y[0:x])
 y=y[x:]

And here's an example run:

enter a sentence Welcome to the jungle!
enter a number 5
Welco
me to
 the 
jungl
e!

CodePudding user response:

y=input('enter a sentence ')
x=int(input('enter a number '))
[y[i:i int(x)] for i in range(0, len(y), int(x))]

enter a sentence Welcome to the jungle.
enter a number 5
['Welco', 'me to', ' the ', 'jungl', 'e.']

OR simply:

y=input('enter a sentence ')
x=int(input('enter a number '))
for i in range(0, len(y), int(x)):
    print(y[i:i int(x)])
enter a sentence Welcome to the jungle.
enter a number 5
Welco
me to
 the 
jungl
e.

CodePudding user response:

string = input('enter a sentence ')
number = int(input('enter a number '))

while True :

    if string == "" :

        break

    print(string[:number])

    string = string[number:]

print(string)

Maybe you can try that.

  • Related