I am using python 2.7 and i'm trying to find a solution to this problem, when i get a string from a certain function i need to switch between the first and the last character. for example if the string is "hello" it should return as "oellh" slicing won't work and i cant just replace the characters like i will normally do because i dont know what the string is going to be or how long it would be. I thought about replacing between the character in position 0 with the character in position -1 but i cant find something that will enable me to do it. Does anyone have any suggestions?
4 Answers
s[-1] + s[1:-1] + s[0] if len(s) > 1 else s
This will swap everything except for the edge cases of '' and 'a' (single char).
The snippet of code below slices the string into three chunks. The end chunks swap the first and last letters while the middle chunk grabs the middle of the string.
s[-1] + s[1:-1] + s[0]
# Below, I show each chunk in the interpreter.
>>> s = 'hello'
>>> s[-1]
'o'
>>> s[1:-1]
'ell'
>>> s[0]
'h'
You can't slice up a string that's < 2 in length because of index errors and the fact that there is no reason to swap a 1 character string. That is what the if .. else protects against. If you don't understand how if .. else works, read the snippet below.
# This returns expr1 if expr2 is true, otherwise it returns expr3
a = expr1 if expr2 else expr3
# The above expression is the short hand of...
if expr2:
a = expr1
else:
a = expr3
I hope this made sense.

- 2,234
- 1
- 19
- 22
-
yep that worked (: can you explain in words what is the logic? I just couldent figure it out. – user1040563 Nov 10 '11 at 21:20
-
Sure thing... Give me a moment to edit my original entry, adding some commentary. – jaime Nov 10 '11 at 21:55
-
It's identical to the logic in the other answer. "X if Y else Z" means the same thing in Python that "Y ? X : Z" does in some others, and in fact is the *natural word order in English* when you are describing something rather than ordering it - which makes sense here because we have an expression rather than a statement. – Karl Knechtel Nov 10 '11 at 21:59
Strings are immutable so you can't modify them directly, but you can create a new string from an existing one. Try this:
if len(s) < 2:
return s
else:
return s[-1] + s[1:-1] + s[0]

- 811,555
- 193
- 1,581
- 1,452
-
I wonder there is a faster but not more complex way than generating four additional strings,(could reduced one string by str.join). – utdemir Nov 10 '11 at 21:35
Old-fashioned Pythonistas don't need no steenking ternary operators:
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> for s in ('abc', 'ab', 'a', ''):
... print repr(s[-1:] + s[1:-1] + s[:-1][:1])
...
'cba'
'ba'
'a'
''
>>>

- 81,303
- 11
- 141
- 189
SINGLE LINE SOLUTION
Regexes are not as efficient as string replacements, but it should not make a big difference for short strings.
>>> s = 'hello'
>>> print re.sub('^(.)(.*?)(.)$',r'\3\2\1',s)
'oellh'

- 169
- 1
- 5
-
It also gives you added readability by saving the expression using an re.compile for reuse later. Modifying the expression (if necessary) becomes much easier in the future. – shivram.ss Nov 12 '11 at 21:49
-
-1 (1) "There is NOTHING you can't do with a regex" (2) Needs to use re.DOTALL flag (3) `$` matches `\n`, use `\Z` instead – John Machin Nov 12 '11 at 21:57
-
You can't, for example, [parse HTML with regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Where did you get this information from? – Aaron Dufour Nov 14 '11 at 03:47
-
I meant to say for short string operations but I obviously wasn't clear. Agree with your opinions on HTML. I would remove the nothing you can't do from my answer if given a chance :) – shivram.ss Nov 14 '11 at 04:00
-
@JohnMachin: Interesting point about the $ vs \Z. I guess I tailored my regex specifically to his example. – shivram.ss Nov 14 '11 at 04:04
-
@live2bshiv There should be an edit button under your answer. That way you can fix your answer. – Aaron Dufour Nov 14 '11 at 23:06