问题:当一个接受list函数收到string类型值编译器会如何处理?
结论: 会将string类型强制转换成为list类型在进行处理
疑问来源:
今日在阅读pythoncrashcourse中chapter8-Passing a list中的代码段:
def greet_user(names):
"""Display a simple greeting to each user in the list."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_user(usernames)
在敲出代码后突发奇想,如果我直接将string类型传入,的话会得到什么结果?是否会直接将string类型当做list中的一个值处理,直接一次循环结束,在好奇之下我更改了我的代码,做出尝试:
def greet_user(names):
"""Display a simple greeting to each user in the list."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
#usernames = ['hannah', 'ty', 'margot']
usernames = 'usernames'
#print(usernames)
greet_user(usernames)
得到结果:
Hello, U!
Hello, S!
Hello, E!
Hello, R!
Hello, N!
Hello, A!
Hello, M!
Hello, E!
Hello, S!
我就好奇了,为什么会得到这样的结果,于是尝试性的写了以下代码:
usernames = 'usernames'
print(usernames)
但是没有得到预期结果,实际结果如下:
usernames
我重新尝试:
usernames = list('usernames')
print(usernames)
终于得到预期结果:
['u', 's', 'e', 'r', 'n', 'a', 'm', 'e', 's']
从而得出开头结论!