By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,758 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

split a string and build tuple

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
# 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.