Python Forum

Full Version: from string to list to string.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def splice():
    name = raw_input('Enter name and age.\n> ')
    result = name.split()
    add_comma = result[:1] + [', '] + result[1:]
    new = ''.join(add_comma)
    print (new)

splice()
input: John 56
output: John, 56

Is there a better way to do this?
name = 'John 56'
name = name.replace(' ', ', ', 1)
print(name)
result:
Output:
'John, 56'
Alternative:
>>> name = 'John 56'
>>> ', '.join(name.split())
'John, 56'

>>> # As Larz60+ suggest also work without 1
>>> name.replace(' ', ', ')
'John, 56'
Thanks for the help!

I should have asked it this way first but how would I get an output of John Doe, 56 from John Doe 56?
split it up into many white-space separated words (however many there are), and take the last item [-1] as the age and slice all but the last [:-1] one as the name.  suggestion: use a variable name other than name for the input before the name is sliced out.  extra points: check if the last one is a valid age (is '56.1' a valid age?)  more points: take ages like '27 years and 3 months'.
>>> help(str.rsplit)
Help on method_descriptor:

rsplit(...)
   S.rsplit(sep=None, maxsplit=-1) -> list of strings
   
   Return a list of the words in S, using sep as the
   delimiter string, starting at the end of the string and
   working to the front.  If maxsplit is given, at most maxsplit
   splits are done. If sep is not specified, any whitespace string
   is a separator.
str.join() is faster than replace()... I think
(Feb-04-2017, 01:26 PM)wavic Wrote: [ -> ]str.join() is faster than replace()... I think
Replace is faster,there is 1 more function call in(join() + split()).
About 3-sec faster in a 10000000 timeit loop.

Now do this not matter all for this task,
and his last requirement destroy it for replace()  Doh
Quote:would I get an output of John Doe, 56 from John Doe 56?
That's why i did hint about rsplit().
regex also works fine.  But of the various things posted, I would prefer ", ".join(spam.split())


>>> import re
>>> spam = "can you feel it coming in the air tonight"
>>> re.sub(r"\s+", ", ", spam)
'can, you, feel, it, coming, in, the, air, tonight'
'Hold, On'