Python converting string to integer,list ,tuple,set,dictionary and vice versa

In this post we will see some of the ways to convert string to integer,string to list,string to tuple, string to set and string to dictionary.We will also see the vice versa which is to convert int to string ,list to string ,tuple to string , set to string ,and dictionary to string.

Converting string to int ,list , tuple ,set and dictionary

Converting string to integer is easily done using the function int().Here you must make sure that the string consist only of digits since alphabets or any character other than the digits cannot be converted to integer.If there is point in the string you can the function float() to convert the string to floating point type.

>>> st='234'
>>> i=int( st )
>>> i
>>> #String with point
>>> st1='90.567'
>>> i1=int( st1 )  #Error!!
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    i1=int( st1 )
ValueError: invalid literal for int() with base 10: '90.567'
>>> f=float( st1 ) #Work fine
>>> f

Simple isn’t?

String to list

Converting string to list can be done using the function list().

>>> st="new man456"
>>> ls=list( st )
>>> ls
['n', 'e', 'w', ' ', 'm', 'a', 'n', '4', '5', '6']

Here each character in string is converted to item of list.

String to tuple

To convert string to tuple use the function tuple().

>>> st='456 ,800 ,27 nmree'
>>> tp=tuple( st )
>>> tp
('4', '5', '6', ' ', ',', '8', '0', '0', ' ', ',', '2', '7', ' ', 'n', 'm', 'r', 'e', 'e')

Again here all the characters of string is taken as single item of the tuple.

String to set

String to set is converted using the function set().And note since set does not allow duplicate elements if any character is found mroe than once they are neglected.

>>> st="Happy 123 year"
>>> st=set(  st )
>>> st
{'1', '2', ' ', 'p', 'H', 'e', 'a', '3', 'y', 'r'}

String to dictionary

The string conversion to dictionary can be done with dict() and zip() function.However note that dictionary item always consist of key:value pair,so in this case you must provide two strings .The first one will make up the key and the second the value.

More about zip() here: Python zip() function

>>> st1='text!'
>>> st2='New12'
>>> dic=dict( zip(st1 , st2) )
>>> dic
{'t': '1', 'e': 'e', 'x': 'w', '!': '2'}

If you have just one string then you can use the range() function to generate the key using the characters from string as the value of the dictionary.

>>> st='New hype!!!'
>>> dc=dict( zip(range( 11 ) , st) )
>>> dc
{0: 'N', 1: 'e', 2: 'w', 3: ' ', 4: 'h', 5: 'y', 6: 'p', 7: 'e', 8: '!', 9: '!', 10: '!'}

The value provided to range() is the number of characters in the string ‘st’.

More about range() : Python range()

Converting integer,list,set,tuple,dictionary to string

Integer to string

To convert integer to strong use the function str().

>>> i=345
>>> st=str( i  )
>>> st
>>> st1=str( 234.678)
>>> st1

Converting list and set to string

Converting list and tuple to string are similar so we will be discussing them together.

Using the ‘+’ operator

Using ‘+‘(plus) operator if we add all the elements of list or tuple then we get the string.However,this method works only if the elements are character or string themself.If any integer or floating number is found you will get and error.

>>> ls=['34' ,' new' , '990']
>>> ss=ls[0]

The string here not only consist of the elements of the list but also includes the bracket ‘[]’ even coma.But we want only the elements to group together and form the string,so here is what you should do.

>>> ls=[34 ,' new' , 990]
>>> ss=ls[0]+ls[1]+ls[2]
>>> ss
'34 new990'
>>> #From tuple
>>> tp=('23' ,' ' , ' 90.90'  , 'Python rocks!!')
>>> s1=tp[0]+tp[1]+tp[2]+tp[3]
>>> s1
'23  90.90Python rocks!!'
>>> #If one of the element is an integer
>>> ls1=[23 ,' ' , 'New' , '1234']
>>> ss=ls1[0]+ls1[1]+ls1[2]+ls1[3]
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

We cannot add the elements of ls1 to get string since the ls1[0] is an integer and adding int with string type is not allowed.

The most probable solution for this is to convert the integer element to string type first using the str() function and add the elements together.

>>> ls=[23 ,' ' , 'New' , '1234']
>>> s1=str(ls1[0]) + ls1[1] + ls1[2] + ls1[3]
>>> s1
'23 New1234'

Leave a Reply

Your email address will not be published. Required fields are marked *