Home
Python
String join Examples (Get String From List)
This page was last reviewed on Nov 19, 2021.
Dot Net Perls
Join. This method combines strings in a list or other iterable collection. It is called with an unusual syntax form. We call it on the delimiter that will come between the iterables values.
Shows a list
Some info. With join, we reverse the split() operation. We can use a delimiter of zero, one or more characters. Any string can be used—but simple ones are usually best.
String List
First example. Here we use the join() method. The method is called on a string (usually a string literal) and then the list is passed as the argument.
String Literal
Tip Join only places delimiters between strings, not at the start or end of the result. This is different from some loop-based approaches.
Here We merge the strings without a delimiter (by specifying an empty string) and with a delimiter (a comma string).
Shows a list
list = ["a", "b", "c"] # Join with empty string literal. result = "".join(list) # Join with comma. result2 = ",".join(list) # Display results. print(result) print(result2)
abc a,b,c
Integer list. We cannot join together a list of integers. But we can call map() to convert each integer into a string, and then join() the result of map.
Tip We use map() to transform or convert each element. Other operations can be used as well—try passing in a lambda.
map
lambda
list = [10, 20, 30] # Map each integer to a string with str. list_mapped = map(str, list) # Join together with comma. result = ",".join(list_mapped) print(result)
10,20,30
Some notes, performance. It is best to avoid calling join() more than needed. For complex data structures, keep all elements in lists or maps—avoid excessive split() and join calls.
String split
A summary. Join() is called on a string—often a string literal. This syntax confuses most beginning Python developers. But it makes logical sense—we are joining on a delimiter.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 19, 2021 (edit link).
Home
Changes
© 2007-2024 Sam Allen.