Posts: 98
Threads: 43
Joined: Dec 2016
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?
Posts: 12,024
Threads: 484
Joined: Sep 2016
Feb-04-2017, 04:11 AM
(This post was last modified: Feb-04-2017, 04:12 AM by Larz60+.)
name = 'John 56'
name = name.replace(' ', ', ', 1)
print(name) result:
Output: 'John, 56'
Posts: 7,313
Threads: 123
Joined: Sep 2016
Alternative:
>>> name = 'John 56'
>>> ', '.join(name.split())
'John, 56'
>>> # As Larz60+ suggest also work without 1
>>> name.replace(' ', ', ')
'John, 56'
Posts: 98
Threads: 43
Joined: Dec 2016
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 ?
Posts: 4,646
Threads: 1,493
Joined: Sep 2016
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'.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 7,313
Threads: 123
Joined: Sep 2016
>>> 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.
Posts: 2,953
Threads: 48
Joined: Sep 2016
str.join() is faster than replace()... I think
Posts: 7,313
Threads: 123
Joined: Sep 2016
Feb-04-2017, 06:30 PM
(This post was last modified: Feb-04-2017, 06:30 PM by snippsat.)
(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()
Quote:would I get an output of John Doe, 56 from John Doe 56?
That's why i did hint about rsplit() .
Posts: 3,458
Threads: 101
Joined: Sep 2016
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'
Posts: 12,024
Threads: 484
Joined: Sep 2016
|