471,353 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,353 software developers and data experts.

split a string and build tuple

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.
Jul 18 '05 #1
2 4331
In article <40**********************@news.free.fr>,
"GrelEns" <gr*****@NOSPAMyahoo.NOTNEEDEDfr> wrote:
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.

--
-- Lou Pecora
My views are my own.
Jul 18 '05 #2
# 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

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by sck10 | last post: by
8 posts views Thread by ronrsr | last post: by
12 posts views Thread by Siah | last post: by
2 posts views Thread by Lars | last post: by
13 posts views Thread by Chaim Krause | last post: by
reply views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.