join an array of substrings into a string in python

To join an array of substrings into a string in Python, you can use the join() method.

The join() method takes an iterable as its argument and returns a string by concatenating all the elements of the iterable. Here is an example:

main.py
substr_array = ["Hello", "world", "!"]
str_sentence = " ".join(substr_array)
print(str_sentence)
97 chars
4 lines

In the above code, we have an array of substrings substr_array and we want to join them into a sentence string. We use the join() method and pass the array as an argument. The " " argument in join() represents the separator that we want to use between each substring. In this case, we want to use a space as the separator.

The output of the above code will be:

main.py
Hello world !
14 chars
2 lines

Similarly, you can use any other separator such as ,, -, |, etc. by passing it as an argument to the join() method.

gistlibby LogSnag