![]() |
|
[Tut] The Most Pythonic Way to Convert a List to a String - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] The Most Pythonic Way to Convert a List to a String (/thread-95818.html) |
[Tut] The Most Pythonic Way to Convert a List to a String - xSicKxBot - 06-21-2020 The Most Pythonic Way to Convert a List to a String To convert a list Code: lstCode: ''.join(lst)Code: ''.join(str(x) for x in lst)![]() Problem: Given a list of elements. How to convert them to a string? Example: Given the following list of strings. Code: lst = ['a', 'b', 'c']You want to convert the list of strings to the following string: Code: 'abc'What’s the most Pythonic way of converting a list to a string? The answer depends on the nuances. Here’s a quick overview before we dive into each of the methods: https://trinket.io/embed/python/66febeb22d Exercise: Run the code! What’s the most Pythonic way in your opinion? Method 1: Join List of Strings The most straightforward way is to use the Code: string.join(iterable)Code: iterableCode: stringCode: lst = ['a', 'b', 'c']
s = ''.join(lst)The output is the following string: Code: print(s)
# abcDue to its conciseness and efficiency, this is the most Pythonic way of converting a list of strings to a string. However, the join() method expects that you pass a list of strings. If you have a list of non-strings, it will throw an error! Related article: The Ultimate Guide to Python Join Method 2: Join List of Non-Strings with Generator Expression So, what to do if you want to convert a list of general objects to a string? The most Pythonic way to concatenatea list of objects is the expression Code: ''.join(str(x) for x in lst)Code: str(...)Code: join()Code: lst = [1, 2, 3]
s = ''.join(str(x) for x in lst)
print(s)
# 123This general method works for all objects (because all objects implement the Code: __str__Related article: What’s the most Pythonic way to join a list of objects? Method 3: String Concatenation with + Just for the sake of completeness, I want to highlight that you can also concatenate all strings in a list by using the + operator. If you have a list with a few objects, this is a viable option: Code: lst = ['a', 'b', 'c']
s = lst[0] + lst[1] + lst[2]
print(s)
# abcThis is inefficient because each Code: +Code: nCode: n-1Related article: The Code: +This must be slightly modified when concatenating a list of objects to a single string: Method 4: String Concatenation with + and str() Again, if you have a list of objects, you need to convert each object to a string first: Code: # Method 4: String Concatenation with + and str()
lst = [1.0, 2.0, 3.0]
s = str(lst[0]) + str(lst[1]) + str(lst[2])
print(s)
# 1.02.03.0This is very tedious and it deserves to be titled the “least Pythonic way to convert a list to a string”. You should prefer the general Method 2 that’s not only shorter and more efficient, but also more readable and generally applicable. Method 5: Use Map + Join The map function allows you to convert each element to a string first. You can then join the strings using the standard string.join() method on the resulting iterable of strings. Code: lst = [1, 2, 'hello', 3.2]
s = ''.join(map(str, lst))
print(s)
# 12hello3.2This works beautifully for list of objects as well and it’s quite Pythonic. Many Python coders like this functional style—but I don’t consider it the most Pythonic one. Python code should be readable. Guido van Rossum, Python’s creator, tried to avoid functional programming because he didn’t find it readable compared to list comprehension or its generalization “generator expressions” (see Method 2). Related Article: The map() function in Python Method 6: Simple Loop Let’s see what coders who come from another programming language such as Java would do: Code: lst = [1, 2, 'hello', 3.2]
s = ''
for x in lst: s += str(x)
print(s)
# 12hello3.2They’d first create an empty string. Then, they’d add the string representation of each list element to the string until all list elements are added. This is highly inefficient because of the repeated creation of new strings and it needs three lines instead of one. As it’s often the case in Python, you can avoid loops by using Python’s powerful built-in capabilities. Related article:Go vs Python Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |