Search code examples
pythonlistcharacterstring-length

How to count characters in a variable which could contain a list and string


I need to print a heading during the running of a script, e.g. "Test #",k, voltage_list where k could be a string and the voltage list something like [2.45, 2.51]. I want a full count of how many characters are in the line as it would be printed to the console (including spaces, brackets and decimal points).

I can count the individual string chars and can either turn the list contents into strings and combine them or can join them into a string directly.

if the line I need to print ("Test #",k, voltage_list) evaluates to Test # seven [2.45, 2.51] I don't know how to account for the brackets and decimal points and spaces between list elements

Desired output

=========================
my_text more [1.23, 4.56]
=========================

Code

    the_list = [1.23, 4.56]

    mystr = ("my_text", "more", the_list)
    print(mystr)
    print('\n'*2)
    
    
    string_tot = 0
    for elem in mystr:        
        if isinstance(elem, str):
            string_count = len(elem)
            string_tot += string_count + 2
            print("string_tot : ", string_tot)
            print('\n')
        elif isinstance(elem, list):
            print("elem is list")
            elem_list_count = len(elem) + 2
            char_to_string = "".join(map(str, elem))
            print("char_to_string : ", char_to_string)
            list_count = len(char_to_string)
            print("list_count : ", list_count)
  
            string_tot += list_count
            print("string_tot : ", string_tot)
            print('\n')

Solution

  • You can just create your final string and get its length. E.g.:

    the_list = [1.23, 4.56]
    mystr = ("my_text", "more", the_list)
    
    final_line = "{} {} {}".format(*mystr)
    
    print("=" * len(final_line))
    print(final_line)
    print("=" * len(final_line))