In this example, we have a list of strings called words. We want to join these strings together into a sentence, so we use the join() method. We pass the list of strings to the method, and we also pass a separator string, which in this case is a space. The join() method then combines all of the strings in the list with the separator string, resulting in a final sentence.
1. Joining a list of numbers as strings
Python3
numbers = [ 1 , 2 , 3 , 4 , 5 ]
numbers_as_strings = [ str (num) for num in numbers]
result = "-" .join(numbers_as_strings)
print (result)
|
2. Joining a list of sentences into a paragraph
Python3
sentences = [ "This is the first sentence." ,
"This is the second sentence." , "This is the third sentence." ]
paragraph = "\n" .join(sentences)
print (paragraph)
|
Output
This is the first sentence.
This is the second sentence.
This is the third sentence.
3. Joining a list of words into a URL path
Python3
words = [ "blog" , "python" , "efficient" , "string" , "concatenation" ]
path = "/" .join(words)
url = "https://www.example.com/" + path
print (url)
|
Output
https://www.example.com/blog/python/efficient/string/concatenation
4. Joining a list of strings using a custom separator function
Python3
strings = [ "foo" , "bar" , "baz" , "qux" , "quux" ]
def separator_func(index):
return "-" if index % 2 = = 0 else "_"
result = "".join([string + separator_func(i)
for i, string in enumerate (strings)])
print (result)
|
Output
foo-bar_baz-qux_quux-
5. Joining a list of strings using a prefix and suffix
Python3
words = [ "apple" , "banana" , "orange" ]
prefix = "I like to eat "
suffix = "s for breakfast."
result = ", " .join([prefix + word + suffix for word in words])
print (result)
|
Output
I like to eat apples for breakfast., I like to eat bananas for breakfast., I like to eat oranges for breakfast.
6. Joining a list of characters using a custom separator
Python3
chars = [ "a" , "b" , "c" , "d" , "e" , "f" ]
separator = " "
result = separator.join(chars[i] + chars[i + 1 ]
for i in range ( 0 , len (chars) - 1 , 2 ))
print (result)
|
GFact | Most efficient way to Concatenate Strings in Python
Concatenation is an operation that is very frequently used in various problems related to strings. There are multiple methods to concat strings in various languages. Python is also such a language that supports various string concatenation methods. But have you ever wondered which one is the most efficient? If your answer is “YES” then the following post will be helpful to you because in this post we will discuss the most efficient way to Concatenate Strings in Python language.