List items conversion to string in python

My last post about string handling was written in ruby. This time it's a one-liner I use for a private python-powered project.
It is inspired by two StackOverflow answers : how to convert all items in a list to floats
and how to change any data type into a string in python.

If you mix the two answers, the result code is [str(i) for i in <list name>]. Now let's see how to use in an interactive shell and in a PyQt4 example.
python one-liner to convert list content

Interactive example

Here is an interactive example of the code
>>> lst = ['a', 2, 23.25, "aze"]
>>> lst
['a', 2, 23.25, 'aze']
>>> [str(i) for i in lst]
['a', '2', '23.25', 'aze']

PyQt4 example

The iniital issue was to create a TableWidgetItem with values comming from a Sqlite database :
import sqlite3
from PyQt4 import QtGui

conn = sqlite3.connect("test.db")
curs = self.conn.cursor()
curs.execute("SELECT * FROM Movements")
moves = curs.fetchall() 

for move in moves:
  # move now contains mixed integers and strings
  # according to the sqlite columns types
  # So the following will fail with type issues
  # i = QtGui.QTreeWidgetItem(moves)

  items = [str(i) for i in move]
  treeItem = QtGui.QTreeWidgetItem(items)


This is a really simple example on how python can be powerful and efficient. Hope it will help you.


  1. I like your blog, I read this blog please update more content on python, further check it once at python online training


Post a Comment

Popular posts from this blog

How to make a map of variant in C++