如何在 python 中使用 for 循环键入 "line1"、"line2"、"line3"...
How to type "line1", "line2", "line3".... using for loop in python
例如,我想使用“for”循环生成以下输出,让 for 循环自动填充单词 line
:
末尾的数字
line1
line2
line3
line4
line5
line6
line7
以下是在 for
循环中使用“f-strings”和 range()
class 对象的方法:
#!/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-strings”
str.format()
方法,或
- C
printf()
-like %
运算符
Here are demo prints 所有这 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
运行 命令和输出:
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
- 所有“Built-in 函数”的官方 Python 文档。习惯引用这个:https://docs.python.org/3/library/functions.html
- 特别是
range()
class,它创建了一个 range
对象,它允许上面的 for
循环迭代:https://docs.python.org/3/library/functions.html#func-range
您可以使用 f 字符串。\
n = 7
for i in range(1, n + 1):
print(f"line{i}")
例如,我想使用“for”循环生成以下输出,让 for 循环自动填充单词 line
:
line1
line2
line3
line4
line5
line6
line7
以下是在 for
循环中使用“f-strings”和 range()
class 对象的方法:
#!/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-strings”
str.format()
方法,或- C
printf()
-like%
运算符
Here are demo prints 所有这 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
运行 命令和输出:
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
- 所有“Built-in 函数”的官方 Python 文档。习惯引用这个:https://docs.python.org/3/library/functions.html
- 特别是
range()
class,它创建了一个range
对象,它允许上面的for
循环迭代:https://docs.python.org/3/library/functions.html#func-range
- 特别是
您可以使用 f 字符串。\
n = 7
for i in range(1, n + 1):
print(f"line{i}")