So, I have written code to slice a string:
word = "Fred"
n = len(word)
for i in range(n):
for j in range(i+1, n+1):
print(word[i:j])
Which returns:
F
Fr
Fre
Fred
r
re
red
e
ed
d
However, I need it to return the string like this:
Fred
Fre
red
Fr
re
ed
F
r
e
d
What I have tried: I have thought about saving the slices to a list and then sorting them that way, however, that will only sort them alphabetically and that won't work. I'm pretty sure I can tweak the logic somehow to make it work.I have watched as many videos on the subject as I can to no avail. Searched Google. Asked for help in a Python Discord server. And reached out to class mates. I have also sought help on my schools tutoring site. No progress. That is why I have asked here.
How can I make this happen? I need it to return that way regardless of which string I input. Thanks in advance for the help:)
I think you want to reverse the roles of i and j.
word = "Fred"
n = len(word)
for i in range(n, 0, -1):
for j in range(n-i+1):
print(word[j:j + i])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.