0

I am trying to learn how to manipulate strings in python. The algorithm is:

  1. Input a string such as Hello World!.
  2. Left shift the string such that first character of the string is wrapped around to the end of the string with the output as ello World!H. Then the code will to the right shift of the same string.

How can I do this? I am aware of the << and >> bitwise shift operators, however these are for int types only. Would anyone care to point me in the right direction?

I started my code as follows and this is about as far as I can get:

instr = "Hello World!" 
length = len(instr) - 1
firstChar = intstr[1]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

1

just use string slicing

instr = "Hello World!"
new_str = instr[1:] + instr[0]
Qdr
  • 703
  • 5
  • 13
0

The other answers work for your requirement to shift only the first character. But for more generic use case, here is how you would apply their logic to rotate by any digit.

  • if digits > 0: shift to left with rotate
  • if digits < 0: shift to right with rotate
def shift_with_rotate(string, digits):
  # if digits is more than length of string,
  # bring it down to less that len(s) by
  # performing modulo
  digits %= len(string) 
  # input  -> ['0','1','2','3'], d=2
  # return -> ['2','3'] + ['0', '1']
  return string[digits:] + s[:digits]  

# test = "12345678"
# shift_with_rotate(test, 1) -> "23456781"
# shift_with_rotate(test, 3) -> "45678123"
# shift_with_rotate(test, -1) -> "81234567"
# shift_with_rotate(test, -3) -> "67812345"

AnkurSaxena
  • 825
  • 7
  • 11