Discuss / Python / 为什么会出现这种情况呢

为什么会出现这种情况呢

Topic source
在此插入代码

L = ['Bart', 'Lisa', 'Adam'] for i in L: print('Hello,i!')

在此插入代码

结果出现的是 Hello,i! Hello,i! Hello,i!

Mr楷哥

#2 Created at ... [Delete] [Delete and Lock User]

因为引号里面的i是字符串的一部分,不是名为i的变量。

>>> i = 'Bart'
>>> 'Hello, i!'
'Hello, i!'

想要表示变量i所指向的值,要把i拿到引号外面去。

>>> i = 'Lisa'
>>> 'Hello, %s!' % i
'Hello, Lisa!'

牧风先森

#3 Created at ... [Delete] [Delete and Lock User]
print('Hello,i!')

这句只是输出 Hello,i! 这个字符串,想要显示元素i的内容,可以用格式化字符串

print('Hello,%s!' % i)

print('Hello,i!')

这里用了单引号‘’,引号内部就是string直接被print出来


  • 1

Reply