简体   繁体   English

以降序返回字符串的子字符串

[英]Returning Substrings Of A String In Descending Order

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.在 Python Discord 服务器中寻求帮助。 And reached out to class mates.并联系了 class 伙伴。 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.我认为您想颠倒 i 和 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])
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM