Home > Net >  Understanding why join works differently
Understanding why join works differently

Time:06-22

I would like some further insight in how the function join() works differently when using format(), and a list. As you can tell in the bottom, output is very different.

ina = "{a}{aa}{aaa}{aaaa}".format(a = "This ", aa = "is ", aaa = " my", aaaa = " house.")
print("=".join(ina))

list = "_".join(["Mayor in", "is the", "one to, done"])
print(list)

OUTPUT:

T=h=i=s= =i=s= = =m=y= =h=o=u=s=e=.
Mayor in_is the_one to, done

CodePudding user response:

ina = "{a}{aa}{aaa}{aaaa}".format(a = "This ", aa = "is ", aaa = " my", aaaa = " house.")

ina is now a string: "This is my house".

"=".join(ina)

takes every element of the iterable ina, which is a character, and joins it using =.

["Mayor in", "is the", "one to, done"]

is a list.

"_".join(["Mayor in", "is the", "one to, done"])

takes every element of the iterable ["Mayor in", "is the", "one to, done"], which is a string, and joins it using _.

Joining a string (with character as elements) and joining a list (with strings as elements) will typically give different results, unless your list happens to have single characters in it.


As an aside, using list as a variable name in Python is a bad practice: list already has a value. Should some other place in code use list intending to access the list type, the code would fail.

CodePudding user response:

This is because strings are stored as lists of characters. In the first example, ina = "This is my house." which behind the scenes is stored as ['T', 'h', 'i', 's', ' ', 'm', 'y', ' ', 'h', etc.], so join inserts the '=' between each element of the array giving the output you saw.

The second example where you have a list of strings (aka a list of lists of characters) is stored as [['M', 'a', 'y', 'o', 'r', ' ', 'i', 'n'], ['i', 's', ' ', t', 'h', 'e'], ['o', ...]]. join() only operates on the outermost list, so it will only insert '_' in 2 places.

One way you can see this is by using the len() function.

len(ina) would be 18, but len(["Mayor in", "is the", "one to, done"]) would be 3.

  • Related