Use join to join / join the elements (str) of the list.
>>> v = ["Hello", "Python"]
>>> "".join(v)
'HelloPython'
The element must be of type str.
You can concatenate with any character string.
>>> s = ["A", "B", "C", "D"]
>>> "->".join(s)
'A->B->C->D'
join
takes a ** iterable object (iterator) ** as an argument. In other words, anything that can be turned with a ** for statement ** can be received as an argument.
Lists are also a type of iterable, and I gave an example earlier.
There are many other iterable objects.
tuple
>>> " ".join(("Of wild","Poppo","But","appeared!"))
'A thin poppo has appeared!'
dict
If you turn dict with a for statement, the key will be retrieved. The items method cannot be joined as it is because the key and value are retrieved as tuples.
>>> " ".join({"a": 2, "b": 3, "c": 5, "d": 7})
'a b c d'
str
Since str is also iterable, you can join.
>>> "・".join("secret")
'secret'
>>> "".join(str(c) for i in [0,90,1234,5678])
'09012345678'
Occasionally, some people bother to pass a list comprehension to join, but that's not necessary because what the generator expression returns is iterable. The generator expression method is both speedy and memory efficient because it eliminates the process of converting to a list.
>>> "".join(map(str, [0,90,1234,5678]))
'09012345678'
The return value of the map function is an iterable object called a map object, not a list. There is no need to change to list type.
The file object created by the open function is iterable. If you turn it with a for statement, it will be retrieved line by line.
text.txt
Hakodate
Otaru
Sapporo
Furano
Asahikawa
Shiretoko
>>> print("from".join(open("text.txt")))
Hakodate
Otaru from
From Sapporo
Furano from
Asahikawa from
Shiretoko from
Such.
Besides join, there are many functions that take iterable as an argument.
I don't know which function receives iterable. In that case, see the official website or If you are using an IDE such as PyCharm, you will get iterable in predictive conversion.
Recommended Posts