社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何键入“line1”、“line2”、“line3”。。。。在python中使用for循环

Akshay L • 4 年前 • 1714 次点击  

例如,我想使用For循环生成以下输出:

line1
line2
line3
line4
line5
line6
line7
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128147
文章 [ 3 ]  |  最新文章 4 年前
Qwerty
Reply   •   1 楼
Qwerty    4 年前
l=['line1','line2','line3','line4','line5','line6','line7']
for i in l:
    print(i) 
VAS
Reply   •   2 楼
VAS    4 年前

可以使用f字符串\

n = 7
for i in range(1, n + 1):
    print(f"line{i}")
Gabriel Staples
Reply   •   3 楼
Gabriel Staples    4 年前

下面是如何使用“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种方法是:

  1. 格式化字符串文本;又名:“f弦”
  2. 这个 str.format() 方法,或
  3. 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

参考资料:

  1. *****这是一个 杰出的 阅读,我强烈建议你阅读并研究它!: Python String Formatting Best Practices
  2. 所有“内置函数”的官方Python文档。习惯于这样: https://docs.python.org/3/library/functions.html
    1. 这个 范围() 类,它创建了一个 range 对象,该对象允许 对于 循环迭代: https://docs.python.org/3/library/functions.html#func-range