Thursday, April 30, 2015

Convert strings to tuple in python

#Strings to tuple


>>> myname='cam'
>>> tuple(myname)
('c', 'a', 'm')
>>> (myname,) #did you see the trailing comma after myname, ??
('cam',)

#Problem 1
mylist=["('good', 'buono')", "('afternoon', 'pomeriggo')"]

#my list contains two elements and  they are strings not tuples.

>>> from ast import literal_eval

>>> [literal_eval(i) for i in mylist]

[('good', 'buono'), ('afternoon', 'pomeriggo')]


#problem2

#Input : ['aaa','bbb','ccc']
#output:[('aaa',),('bbb',),('ccc',)]

lst = ['aaa','bbb','ccc']
tpl_lst = [(i,) for i in lst]
>>> tpl_lst
[('aaa',), ('bbb',), ('ccc',)]


#problem 3

# Input : '1/2' ==> it's  a string
#output: (1,2)
>>> my_frac='1/2'
>>> my_frac.split('/')
['1', '2']

>>> my_frac = tuple(map(int, my_frac.split('/')))
>>> my_frac
(1, 2)

#problem 4

#Input: s = "a b c d"
#output1: [(a,a),(b,b),(c,c),(d,d)]
#output2:[(a, b), (b, c), (c, d)]

#Solution for output1

>>> s = "a b c d"
>>> w = s.split()
>>> w
['a', 'b', 'c', 'd']
#python 3.x
>>> list(zip(w,w))
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#python 2.7

>>> zip(w,w)
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#Solution 2:

#python 3.x
>>> list(zip(w,w[1:]))
[('a', 'b'), ('b', 'c'), ('c', 'd')]

#python 2.7

>>> zip(w,w[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd')] 
"Check one more example from SO" Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment