How to split value where is comma ?
Rustom Mody
rustompmody at gmail.com
Fri Sep 9 02:20:39 EDT 2016
On Friday, September 9, 2016 at 1:36:24 AM UTC+5:30, Larry Hudson wrote:
> On 09/08/2016 07:57 AM, John Gordon wrote:
> > In Joaquin Alzola writes:
> >
> >> Use the split
> >
> >> a.split(",")
> >> for x in a:
> >> print(x)
> >
> > This won't work. split() returns a list of split elements but the
> > original string remains unchanged.
> >
> > You want something like this instead:
> >
> > newlist = a.split(",")
> > for x in newlist:
> > print(x)
> >
>
> Even easier...
>
> for x in a.split(','):
> print(x)
In all probability, what is required is just: a.split(','); no for, no print
And unfortunately none of the answers (that I see) describe the spectrum of
what one may really want
a.split(',')
set(a.split(','))
Less likely (in this case) but important for a learner to be aware of:
Counter(a.split(',')
And if the original 'a' looked something like
>>> a="p:1,q:2,r:42"
then you probably want something like:
>>> {k:v for item in a.split(',') for k,v in [item.split(':')]}
{'q': '2', 'p': '1', 'r': '42'}
>>>
In all cases the print is irrelevant and unnecessary
And if we insist on interpreting the OP request for replacing comma by newline
(almost always a misconceived request), one can do:
>>> a="p,q,r"
>>> str(a.replace(',','\n'))
'p\nq\nr'
Sure one can go one step further and do:
>>> print str(a.replace(',','\n'))
p
q
r
But this is almost always not what the requester wants (even if he thinks it is)
[Personal note: When I was a kid I thought that doctors removed fever by sticking
a thermometer into one’s mouth.
Those who teach that programming needs to start with writing print statements
are the same except for not having the excuse of being kids]
More information about the Python-list
mailing list