Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string and add into `tuple`

Tags:

python

I know of only two simple ways to split a string and add into tuple

import re

1. tuple(map(lambda i: i, re.findall('[\d]{2}', '012345'))) # ('01', '23', '45')

2. tuple(i for i in re.findall('[\d]{2}', '012345')) # ('01', '23', '45')

Is there other simple ways?

like image 478
tomas Avatar asked Feb 14 '12 16:02

tomas


2 Answers

I'd go for

s = "012345"
[s[i:i + 2] for i in range(0, len(s), 2)]

or

tuple(s[i:i + 2] for i in range(0, len(s), 2))

if you really want a tuple.

like image 175
Sven Marnach Avatar answered Oct 22 '22 21:10

Sven Marnach


Usually one uses tuples when the dimensions/length is fixed (with possibly different types) and lists when there is an arbitrary number of values of the same type.

What is the reason to use a tuple instead of a list here?

Samples for tuples:

  • coordinates in a fixed dimensional space (e.g. 2d: (x, y) )
  • representation of dict key/value-pairs (e.g. ("John Smith", 38))
  • things where the number of tuple components is known before evaluating the expression
  • ...

Samples for lists:

  • splitted string ("foo|bar|buz" splited on |s: ["foo", "bar", "buz"])
  • command line arguments (["-f", "/etc/fstab")
  • things where the number of list elements is (usually) not known before evaluating the expression
  • ...
like image 41
Johannes Weiss Avatar answered Oct 22 '22 20:10

Johannes Weiss