0

First question ever of probably many more to come. I have a simple python problem that I solved that I will post below, along with my answer. I was wondering if there were any more elegant answers, as I feel like this could be solved more eloquently.

Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2.

left2('Hello') → 'lloHe'

left2('java') → 'vaja'

left2('Hi') → 'Hi'

Here is the code I came up with:

def left2(str):
  first = list(str)
  first.insert(len(first),first.pop(0))
  first.insert(len(first),first.pop(0))
  x = ''.join(first)
  return x

1 Answers1

1

You can slice the string and concatenate the slices instead:

def left2(s):
    return s[2:] + s[:2]
blhsing
  • 91,368
  • 6
  • 71
  • 106