例如,我希望使用" For“循环生成下面的输出,让for循环自动填充单词line末尾的数字。
line1
line2
line3
line4
line5
line6
line7发布于 2022-03-07 05:32:45
您可以使用f字符串。
n = 7
for i in range(1, n + 1):
print(f"line{i}")发布于 2022-03-07 05:31:53
下面是如何在一个range()循环中使用“f-string”和for类对象来完成这个任务:
#!/usr/bin/python3
END_NUM = 7
for i in range(1, END_NUM + 1):
print(f"line{i}")运行命令:
./for_loop_basic_demo.py输出:
line1
line2
line3
line4
line5
line6
line7更进一步:3种打印方法
我知道用Python打印格式化字符串的三种方法是:
str.format()方法,或printf()-like %算子这是演示打印与所有3种技术一起为您显示每一种技术:
#!/usr/bin/python3
END_NUM = 7
for i in range(1, END_NUM + 1):
# 3 techniques to print:
# 1. newest technique: formatted string literals; AKA: "f-strings"
print(f"line{i}")
# 2. newer technique: `str.format()` method
print("line{}".format(i))
# 3. oldest, C-like "printf"-style `%` operator print method
# (sometimes is still the best method, however!)
print("line%i" % i)
print() # print just a newline char运行cmd并输出:
eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py
line1
line1
line1
line2
line2
line2
line3
line3
line3
line4
line4
line4
line5
line5
line5
line6
line6
line6
line7
line7
line7参考文献:
range()类,它创建一个允许上述for循环迭代的range对象:https://docs.python.org/3/library/functions.html#func-rangehttps://stackoverflow.com/questions/71376733
复制相似问题