下面是如何使用“f字符串”和
range()
类中的对象
for
对于_loop_basic_演示。py:
#!/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打印格式化字符串的3种方法是:
-
格式化字符串文本;又名:“f弦”
-
这个
str.format()
方法,或
-
C
printf()
-就像
%
操作人员
以下是三种技术的演示图片,为您展示每种技术:
#!/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
参考资料:
-
*****这是一个
杰出的
阅读,我强烈建议你阅读并研究它!:
Python String Formatting Best Practices
-
所有“内置函数”的官方Python文档。习惯于这样:
https://docs.python.org/3/library/functions.html
-
这个
范围()
类,它创建了一个
range
对象,该对象允许
对于
循环迭代:
https://docs.python.org/3/library/functions.html#func-range