1

the output if given a string, "abcdefg" of length 7 as example, should print out 7 lines like:

abcdefg
bcdefga
cdefgab
defgabc
efgabcd
fgabcde
gabcedf

but I seem to be missing the boat after many many hours of various loops and print statements

s = str("abcdefg")
print(s)
print()
for i in range(len(s)):
    new_s = s[:i+1] + s[-i:] + s[-i]
    print(new_s)

I get this:

abcdefg

aabcdefga
abgg
abcfgf
abcdefge
abcdedefgd
abcdefcdefgc
abcdefgbcdefgb
MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31
craftbrews
  • 11
  • 2

2 Answers2

2

You're overcomplicating this. The proper expression is just

new_s = s[i:] + s[:i]

slicing is inclusive of the start index, and exclusive of the end index. This above expression guarantees to keep the length of the result the same as the input list, just swapping variable parts of it.

Note that the first new_s value is the original string itself. No need to print it at the start of the program.

The result is:

abcdefg
bcdefga
cdefgab
defgabc
efgabcd
fgabcde
gabcdef

slicing in detail: Understanding slice notation

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

the loop could be like:

s_len = len(s)
for i in range(s_len):
    s = s[1:] + s[0]
    print(s)
Rem
  • 1
  • 2