+ 1
How to use join() work? (Python)
How can I use the join() function? I am trying to concatenate converted int # str(some_int) into a list. That come from a for loop. I am finding it difficult to explain, but if someone could give me a clear example of how join() can be put to use, I would be very grateful.
3 Antworten
+ 4
First you have to define a join string.
Let it be '-'.
Then you write:
'-'.join(...
which means:
'Take - and use it to join up...'
and then comes any iterable, be it a list, a tuple ... as long as it contains strings. Or just a string, which is also made of strings.
'-'.join(['a', 'b', 'c'])
And that's all there is to it.
Result:
'a-b-c'
+ 1
I have been working on understanding it more and have written this answer to my own posted question :)
just copy paste this code and run it
#the join() function is used on strings
#is it to join a list (of strings) together, either with or without another string as a separator
thisStrLst = ["one", "two", "three"]
print(", ".join(thisStrLst))
#the fact that the list has the same spacing as the output is because of the part before the .join() (the ", ") and not because of the list.
#you can see an example below of a different separator; " + "
thisStrLst = ["one", "two", "three"]
print(" + ".join(thisStrLst))
#you can also use a variable here for the first part of the join()
#of course you need to define the variable first and this needs to be a string!
thisStrLst = ["one", "two", "three"]
cmaSpcStr = ", "
print(cmaSpcStr.join(thisStrLst))
#if you print lists it will look like
fibStrLst = ["1","1","2","3","5","8"]
print("a printed list looks like: " + str(fibStrLst))
#so what if you want to use that list as one line of all numbers together? Use join as below
#the separator is simply a string with no space or letter/number in it; ""
print("".join(fibStrLst))
#you can even use join() on a string (a string is a series of strings). this, counterintuitively doesn't join letters/words/etc, but takes a string apart and puts them in a order with a separator between the letters.
print(", ".join("spam"))
0
thanks!