-1

I have a variable string, example

a = 'swift'

and if I shift all characters to the left 1 time it becomes a = 'wifts' and if I shift to right 2 times it becomes a = 'tswif'

How to do this? I tried this function:

a = 'swift'
for x in range(len(a)-1):
    a[x+1]

and the result is 'wift'

I expect the output if I shift to left 1 times it becomes a = 'wifts' and if I shift to right 2 times it becomes a = 'tswif'

Nico
  • 9
  • 4
  • You certainly didn't try the 'function' you pasted here, as this would just give an error before doing nothing. Please paste your real code here. – Thierry Lathuille Aug 22 '19 at 14:45
  • @ThierryLathuille that is my real code, just like that – Nico Aug 22 '19 at 14:48
  • see https://stackoverflow.com/questions/48607319/rotating-strings-in-python – Dan Aug 22 '19 at 14:49
  • @Nico The first problem is that a is not a string, the interpreter has no idea what `swift` is, it should be `"swift"`. Second is you're no reassigning anything. Other than that, you're not too far from an answer. – ofthegoats Aug 22 '19 at 14:49
  • `a = swift` would cause a NameError, unless you have defined a `swift` variable before. Also, `a[x+1]` just does nothing, so there is no way you would get a result. So, please edit your question. – Thierry Lathuille Aug 22 '19 at 14:50
  • @PioKozi sorry i just edited my question – Nico Aug 22 '19 at 14:57
  • @Nico There is no way the code in your question can produce what you say it does. Run it exactly as you pasted it and see how it doesn't output anything. So, as already requested, please provide us with a [mcve]. – Thierry Lathuille Aug 22 '19 at 15:00

2 Answers2

0

You don't need a for loop, you can simply recreate the string concatenating the left and right part:

a = 'swift'
shift_amount = 2
a_shifted_left  = a[shift_amount:] + a[:shift_amount]
a_shifted_right = a[-shift_amount:] + a[:-shift_amount] 
Giampietro Seu
  • 786
  • 9
  • 16
0

Expanded on the answer from here:

def shifting(string, number):
    return string[-number:] + string[:-number]

negative numbers are left shifts, and positive numbers are right shifts

rinkert
  • 6,593
  • 2
  • 12
  • 31
ofthegoats
  • 295
  • 4
  • 10