了解为什么加入的工作方式有所不同
我希望进一步了解函数join()
使用format()
和列表时的工作方式不同。正如您可以在底部所说的那样,输出非常不同。
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)
输出:
T=h=i=s= =i=s= = =m=y= =h=o=u=s=e=.
Mayor in_is the_one to, done
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ina
现在是一个字符串:“这是我的房子”
。将iTable
ina
的每个元素(这是一个角色)获取,并使用=
加入它。是一个清单。
将iTable
的每个元素[“市长”为“”,“一个”,“一个”,“完成”]
,它是一个字符串,并使用_
加入它。加入字符串(带有字符为元素)并加入列表(带有字符串作为元素)通常会给出不同的结果,除非您的列表恰好在其中有单个字符。
顺便说一句,在Python中使用
list
作为变量名是一个不好的做法:list
已经具有一个值。如果代码中的其他位置<代码>列表打算访问列表类型,则代码将失败。ina
is now a string:"This is my house"
.takes every element of the iterable
ina
, which is a character, and joins it using=
.is a list.
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 uselist
intending to access the list type, the code would fail.这是因为字符串被存储为字符列表。在第一个示例中,ina =“这是我的房子”。在幕后存储为['t','h','i','s','','','y','',','','h'等。 '='数组的每个元素之间给出了您看到的输出。
您拥有字符串列表(又称字符列表)的第二个示例被存储为[['m','a','y','','o','r',',',','i i' ,'n'],['i','s','',t','h','e'],['o',...]]。 join()仅在最外面的列表上运行,因此它仅在2个位置插入'_'。
您可以看到的一种方法是使用Len()函数。
Len(Ina)是18岁,但是Len([[“市长”,“是”,“一个to,完成”)是3。
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.