Fiona Kwok
Fiona Kwok

Reputation: 87

"Reverse" input in Python

What I want isn't a full reversal of letters but just the order of inputted data.

For example:

raw_input('Please type in your full name')

... John Smith
How do I output this as Smith John?

Upvotes: 0

Views: 3000

Answers (3)

Demian Brecht
Demian Brecht

Reputation: 21368

A small variation on @nnenneo's answer, but this is what I would have done:

>>> s = raw_input('Please type in your full name: ')
Please type in your full name: foo bar
>>> ' '.join(s.split(' ')[::-1])
'bar foo'

Upvotes: 2

samfrances
samfrances

Reputation: 3685

You could do it like this:

name = raw_input('Please type in your full name')
name = name.split()
print name[-1] + ',', ' '.join(name[:-1])

This is in Python 2, but since you're using raw_input, I think that's what you want. This method works if they enter a middle name, so "Bob David Smith" becomes, "Smith, Bob David".

Upvotes: 2

nneonneo
nneonneo

Reputation: 179412

Simply split the string into a list (here I use ' ' as the split character), reverse it, and put it back together again:

s = raw_input('Please type in your full name')
' '.join(reversed(s.split(' ')))

Upvotes: 8

Related Questions