Python Forum
Converting list elements and sublists from int to str
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting list elements and sublists from int to str
#5
A recursive version, be careful with dictionary keys.
test_data = ['Cities', 14, 'WACC', (32, 'KHI', 208.55567), ['Stat', 14, 'RS0'],
           {'one': 1, 2: [1, 2], (1, 2, 3, 4): ('this', 'that', 10)},
           {1, 2, (3.0, 3.5,), 4}]


def all_strings(data):
    if type(data) == list:
        items = []
        for item in data:
            items.append(all_strings(item))
        return items
    
    elif type(data) == tuple:
        return tuple(all_strings(list(data)))
    
    elif type(data) == dict:
        new_dict = {}
        for key, value in data.items():
            new_dict[all_strings(key)] = all_strings(value)
        return new_dict
    
    elif type(data) == set:
        return set(all_strings(list(data)))

    else:
        return str(data) 


print(all_strings(test_data))
Output:
['Cities', '14', 'WACC', ('32', 'KHI', '208.55567'), ['Stat', '14', 'RS0'], {'one': '1', '2': ['1', '2'], ('1', '2', '3', '4'): ('this', 'that', '10')}, {'4', '2', '1', ('3.0', '3.5')}]
Reply


Messages In This Thread
RE: Converting list elements and sublists from int to str - by Yoriz - Mar-10-2019, 06:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 468 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 496 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Checking if a string contains all or any elements of a list k1llcod3 1 1,119 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 2,013 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,173 May-17-2022, 11:38 AM
Last Post: Larz60+
  Why am I getting list elements < 0 ? Mark17 8 3,174 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,147 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 2,289 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 1,986 Jul-11-2021, 09:58 AM
Last Post: perfringo
  Converting a list to dictinary tester_V 8 2,737 Jul-02-2021, 09:04 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020