A very pythonic and practical way to do it is by using the string join()
method:
str.join(iterable)
The official Python documentations says:
Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.
How to use it?
Remember: this is a string method.
This method will be applied to the str
above, which reflects the string that will be used as separator of the items in the iterable.
Let's have some practical example!
iterable = "BINGO"
separator = " " # A whitespace character.
# The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'
In practice you would do it like this:
iterable = "BINGO"
" ".join(iterable)
> 'B I N G O'
But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.
iterable = ['B', 'I', 'N', 'G', 'O']
" ".join(iterable)
> 'B I N G O'
What happens if you use a hyphen as a string instead?
iterable = ['B', 'I', 'N', 'G', 'O']
"-".join(iterable)
> 'B-I-N-G-O'