1

Let´s say I have a one-word string ("Hello") and I wanted to swap the first and last letter so I´d do this:

s="Hello"
l=list(s)
l[0],l[len(l)-1]=l[len(l)-1],l[0]
print("".join(l))

But, what if I had to swap the first and last letter in every word of the string:"Hello World" , so that I would get "oellH dorlW".

I was thinking using nested lists but it seems overcomplicated.

Felka98
  • 109
  • 4

3 Answers3

3

Strings are immutable, so you can create a new one by slicing:

s = "Hello"
>>> s[-1] + s[1:-1] + s[0]
"oellH"

To do multiple words, split and rejoin as follows:

s= "Hello World"
>>> ' '.join(word[-1] + word[1:-1] + word[0] for word in s.split())
'oellH dorlW'
Alexander
  • 105,104
  • 32
  • 201
  • 196
2

You can split your string, swap letters for each word and .join() it back together:

# example is wrong, does not swap, only puts first in the back. see below for fix
text = ' '.join( t[1:]+t[0] for t in "Hello World".split() )
print (text)

Output:

 elloH orldW

This uses list comprehensionst to extract each splitted word (t) - list slicing to move the front letter to its back (t[1:]+t[0]) and ' '.join() to make the list of strings back to a string.

Links:

It also works for longer strings:

elloH orldW si a eallyr verusedo trings ermt - orF ureS !

As pointed out by @Accumulation I misread the question - my example simply puts the first letter to the end of the string thats only halve the work done for swapping first and last letter:

# t[-1] is the last character put to the front, 
# followed by t[1:-1] 1st to (but not including) the last character 
# followed by t[0] the first character
text = ' '.join( t[-1]+t[1:-1]+t[0] for t in "Hello World".split() )
print (text)

Output:

oellH dorlW 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Elegant! Would definitely take a few lines for Java – Peter Chaula Sep 17 '18 at 17:21
  • 1
    The OP wants "oellH dorlW", not "elloH orldW". – Acccumulation Sep 17 '18 at 17:32
  • Yeah, I was actually looking for something a bit different but I totally get your logic,thanks for the references too – Felka98 Sep 17 '18 at 17:41
  • 1
    His example is perfectly consistent with the wording of the question. Even without the example, I would interpret "swap the first and last letter" as `final_string[first],final_string[last = initial_string[last],initial_string[first]`. Perhaps you should add the possibility that your understanding of "swap" is incorrect to your list of hypotheses. – Acccumulation Sep 17 '18 at 17:51
  • @Acccumulation - fixed it, misread it - thanks for putting my hesitent nose into it :) – Patrick Artner Sep 17 '18 at 17:59
1
    string  = "Hello Planet Earth"

Make a list of words by splitting on space char

    words = string.split(" ")

Then iterate on that list with your script

    for word in words:
        l = list(word)
        l[0], l[len(l) - 1] = l[len(l) - 1], l[0]
        print("".join(l))
hjuste
  • 130
  • 1
  • 12