How To Convert Python List / Tuple Element To String

This example tell you how to convert a python list element to a python string, the list data can be pure string data or mix data type such as string, number and boolean. The methods below also applicable to python tuple ( read only python list ), just replace [ ] to ( ).

Below source code has three functions, the first function convert a pure string list, the other two function convert mixed data type list.

For performance testing, we loop for 100000 times for each function, and record the cost time. We get below result.

  1. convert_string_list_to_str_join() function use 1256 milliseconds. This is the fastest method.
  2. convert_mixed_list_to_str() function use 9476 milliseconds.
  3. convert_mixed_list_to_str_by_loop() function use 2013 milliseconds.
'''
Created on Aug 24, 2018
@author: zhaosong
'''

import time

# Get current system time in million seconds.
def get_current_time_in_millions():
    ret_millis = int(round(time.time() * 1000))
    print(ret_millis)
    return ret_millis

# When the list is a pure string data list, then use str.join method to convert.
def convert_string_list_to_str_join():
    tmp_list = ['hello', 'world', '!']
    # Use str.join method
    tmp_str = ' '.join(tmp_list)
    print(tmp_str)

# When the list data type is mixed with string, number and boolean.    
def convert_mixed_list_to_str():
    tmp_list = ['hello', 9, 'world', 10, '!', True]
    tmp_str = str(tmp_list)
    tmp_str = tmp_str.replace(",", " ")
    tmp_str = tmp_str.lstrip("[")
    tmp_str = tmp_str.rstrip("]")
    print(tmp_str)

   
# You can also get the list string by loop in it.    
def convert_mixed_list_to_str_by_loop():
    tmp_str = ''
    tmp_list = ['hello', 9, 'world', 10, '!', True]

    for item in tmp_list:
        tmp_str += str(item) + ' '

    print(tmp_str)     

if __name__ == '__main__':
    # Get start time.
    start_time = get_current_time_in_millions()

    # Loop for a long time to test each convert method efficiency.
    for i in range(100000):
        #convert_string_list_to_str_join()
        #convert_mixed_list_to_str()
        convert_mixed_list_to_str_by_loop()
    
    # Get end time.
    end_time = get_current_time_in_millions()

    # Calculate and print the delta time.
    print("delta time = " + str(end_time - start_time))

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.