split a string and build tuple

G

GrelEns

hello,

i'm looking for a pythonic and obvious way to do the following :

having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
....) ?
(a kind of splitting and grouping in an elegant way)

i think that list comprehension or "zip" could maybe help but i just can't
get it work,

thanks.
 
J

Jonathan Daugherty

# having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
# how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
# ...) ?
# (a kind of splitting and grouping in an elegant way)
import string
s = "w1 w2 w3 w4 w5 w6 w7 w8"
x = string.split(s)
x ['w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8']
for index in range(0, len(x), 3):
.... print x[index:index + 3]
....
['w1', 'w2', 'w3']
['w4', 'w5', 'w6']
['w7', 'w8']

--

Jonathan Daugherty
http://www.cprogrammer.org

"It's a book about a Spanish guy called Manual, you should read it."
-- Dilbert
 
L

Lou Pecora

"GrelEns said:
hello,

i'm looking for a pythonic and obvious way to do the following :

having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
...) ?
(a kind of splitting and grouping in an elegant way)

i think that list comprehension or "zip" could maybe help but i just can't
get it work,

thanks.

Since it is space-separated use the Python function 'split' to get a
list of the separate "words." Then you can group them however you like
using list functions.
 

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
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top