user2498805 user2498805 - 1 year ago 85
Python Question

How to Swap First and Last Characters from Input in Python

I am brand new to programming, learning Python3 from an online course. This exercise asks me to write a program which reads a string using

, and outputs the same string but with the first and last character exchanged (example: Fairy becomes yairF). There is likely a simpler way to do this with more advanced functions, however, for the purposes of this exercise, I am supposed to write the program using only classes, substrings and indices. Here is what I have now:

myString = input()
newString = (myString[1:len(myString)-1])

Using the example of input 'Fairy', this outputs 'y air F', which is not what I'm looking for. I also tried

myString = input()
newString = (myString[1:len(myString)-1])
newString[0] = myString[len(myString)-1]
newString[len(newString)-1] = myString[0]

However, line three gave me:
TypeError: 'str' object does not support item assignment
. So I'm guessing I can't assign new values to places in an index. My other approach, below, also gave me an error:

myString = input()
newString = (myString[1:len(myString)-1])
lastString = str(myString[len(myString)-1],newString,myString[0])

Line three gave me:
TypeError: decoding str is not supported
, so it seems that I can't combine them that way. Any tips on handling this?

Answer Source

Try this:

>>> temp = "abcde"
>>> temp[1:-1]
>>> temp[-1:] + temp[1:-1] + temp[:1]

In short, python has magnificent string slicing syntax. You can do magic with it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download