Home > Back-end >  How can I shorten this code (for loop help)
How can I shorten this code (for loop help)

Time:10-22

string1 = str(input("Type a word"))
for i in range(len(string1)):
    print(string1[-1 i], end= "")
print('')
for i in range(len(string1)):
    print (string1[-2 i] , end= "")
print('')
for i in range(len(string1)):
    print (string1[-3 i] , end= "")
print('')
for i in range(len(string1)):
    print (string1[-4 i] , end= "")
print('')
for i in range(len(string1)):
    print (string1[-5 i] , end= "")

How can I shorten this code? It seems highly inefficient, and I think it could be much much shorter. Also the amount of letters is limited because you have to add another loop for an additional letter. Any help would be much appreciated, thanks.

CodePudding user response:

Only one loop.

string1 = str(input("Type a word"))
for i in range(1,len(string1) 1):
    print(string1[-i:]   string1[:-i])

CodePudding user response:

To rotate a string slice of the last letter and put it in the front:

s = s[-1] s[:-1]

Example:

word = "Example"

# we do not care about the letters, just want to loop one time for each letter
for _ in word:
    print(word)
    word = word[-1]   word[:-1]

Output:

Example
eExampl
leExamp
pleExam
mpleExa
ampleEx
xampleE

CodePudding user response:

Try this:

a = str(input("Type a word"))
for i in range(1,len(a)):
    print(a[-i:] a[:-i])

CodePudding user response:

Python's range function can be used to generate the index starting numbers that you're using (-1, -2, etc.).

It accepts a step parameter that can be used to count backwards:

string1 = str(input("Type a word"))

for n in range(-1, -6, -1):
  for i in range(len(string1)):
    print(string1[n i], end= "")
  print('')
  • Related