String question

A

Andreu

I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.

Andrew.
 
T

Tim Golden

Andreu said:
I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.

That would be:

str1 = "The quick brown fox jumps"
v1, v2, v3, v4, v5 = str1.split ()

TJG
 
C

cokofreedom

I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.

Andrew.

Well a straight copy would be...
Hello,

However I would make a list of it.
v_list = example.split()
print v_list ['Hello,', 'how', 'are', 'you']
for word in v_list:
print word
Hello,
how
are
you

That seems to me to be the more pythonic way to do it, since it is
dynamic.
 
A

Andreu

Yes, ... don't ask me why, but in fact v1,v2,v3 = str1.split()
does not seem to work. My original problem was I forgot about
the parenthesis as Tim point out. So I ended up converting to a
list as in: v = str1.split() and accessing the elements using
v[0] v[1] ect...it is working now. Thanks.

Andreu.
 
C

cokofreedom

Andreu said:
Yes, ... don't ask me why, but in fact v1,v2,v3 = str1.split()
does not seem to work. My original problem was I forgot about
the parenthesis as Tim point out. So I ended up converting to a
list as in: v = str1.split() and accessing the elements using
v[0] v[1] ect...it is working now. Thanks.

v1,v2,v3 = str1.split() will only work if there are exactly three things in
str1.

Traceback (most recent call last):

'a test'

-Mark

In Python 3k I believe you can put a * next to one of the variables to
hold multiple arguments. That'll be aidful!
 
T

Terry Reedy

In Python 3k I believe you can put a * next to one of the variables to
hold multiple arguments. That'll be aidful!

IDLE 3.0b1
>>> a,b,*c=[1,2,3,4,5]
>>> c [3, 4, 5]
>>> a,*b,c = [1,2,3,4,5]
>>> b [2, 3, 4]
>>> a,b,*c=[1,2]
>>> c
[]

Augmented assignment is quite similar to argument passing:
at most one starred target;
at least as many items as un-starred targets (as now).

tjr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top