• Python基础:输入输出详解-输出字符串格式化


    在这里插入图片描述

      Python中的输入和输出是编程中非常重要的方面。

    1. 输入输出简单介绍

    1.1 输入方式

      Python中的输入可以通过input()函数从键盘键入,也可以通过命令行参数或读取文件的方式获得数据来源。

    1)input()示例

      基本的input()函数,会将用户在终端(键盘)输入的内容作为字符串返回。

    user_input = input("请输入内容:")
    
    • 1

      通过类型转换为其他数据类型,如:
      使用 int() float() 函数将用户输入的内容转换为整数或浮点数。

    # 获取用户输入的整数
    user_input = int(input("请输入整数:"))
    
    # 获取用户输入的浮点数
    user_input = float(input("请输入浮点数:"))
    
    • 1
    • 2
    • 3
    • 4
    • 5

      使用eval() 函数(不推荐,慎用)
      eval() 函数用于执行以字符串形式给出的 Python 表达式,并返回表达式的结果。
      注意:使用 eval() 函数时要非常小心,特别是当从不受信任的来源获取输入时。不建议直接将用户输入传递给eval() 函数,因为它可能执行任意的 Python 代码,包括潜在的危险操作。最好是在确定输入是安全的情况下使用 eval()

    """
    用户可以输入任何合法的数学表达式,比如 "2 + 3 * 4"。eval() 函数会将输入的字符串作为 Python 表达式来计算,并输出结果。使用 try-except 块来捕获可能的异常,以防止输入的表达式引发错误。
    """
    
    # 获取用户输入的数学表达式并计算结果
    expression = input("请输入一个数学表达式:")
    try:
        result = eval(expression)
        print("计算结果:", result)
    except Exception as e:
        print("发生错误:", e)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2) 命令行参数

      通过命令行参数输入是一种常见的方式,特别是当你想在运行脚本时提供输入而不交互地输入时。
      演示如何通过命令行参数输入:

    # 文件名: script.py
    
    import sys
    
    # 获取命令行参数
    # 注意:sys.argv[0] 是脚本的名称,而实际的参数从 sys.argv[1] 开始
    if len(sys.argv) < 2:
        print("请提供一个参数(例如:python script.py 输入内容)")
    else:
        # 第一个命令行参数是输入的内容
        user_input = sys.argv[1]
        print("您输入的内容是:", user_input)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

      在命令行中运行这个脚本,例如:

    python script.py Hello
    
    • 1

      输出应该是:

    您输入的内容是: Hello
    
    • 1

      通过sys.argv 获取命令行参数,如果没有提供足够的参数,脚本会输出一个提示。第一个参数是脚本的名称,实际的输入参数从第二个开始。

    3)通过文件读取方式

      使用 open() 函数来打开文件,并使用read() 方法来读取文件的内容。

    # 打开文件
    file_path = 'example.txt'
    with open(file_path, 'r') as file:
        # 读取整个文件内容
        content = file.read()
        print("文件内容:")
        print(content)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

      open(file_path, 'r') 打开一个名为 'example.txt'的文件进行读取。使用 with语句可以确保在文件使用完毕后正确关闭。read() 方法用于读取整个文件的内容,并将其存储在变量 content中,然后通过 print() 函数输出文件内容。

    1.2 输出方式

      在 Python 中,主要使用 print() 函数进行输出。print() 函数可以打印字符串、数字和其他数据类型的内容到控制台。

    2. 复杂的输出格式

      程序的输出有几种显示方式,数据既可以输出供人阅读,也可以写入文件备用。
      格式化输出包括以下几种方法:
      1)使用“格式化字符串字面量”
      2)使用str.format()方法
      3)手动格式化字符串
      4)旧式字符串格式化方法
      当你进行调试并想要快速显示变量的值时,可以使用 repr()str() 函数将变量转化为字符串。这两个函数的选择取决于你对输出字符串的期望:
      str()函数: 返回一个供人阅读的字符串。这意味着输出通常更为友好,适合直接展示给最终用户查看。
      repr() 函数: 生成适于解释器读取的字符串,即如果没有等效的语法,会强制执行 SyntaxError。这在调试过程中更有用,因为它提供更多的细节,有助于理解对象的内部结构。
    在一般情况下,数字、列表、字典等结构的值,使用str()repr() 函数输出的表现形式是相似的。但对于自定义类,你可以通过实现 __str____repr__ 方法来定义它们的输出形式。下面是一个简单的例子:

    class Example:
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return f"Example with value: {self.value}"
        def __repr__(self):
            return f"Example({self.value})"
    
    # 创建一个示例对象
    example_obj = Example(42)
    
    # 使用 str() 输出
    print(str(example_obj))  # 输出: Example with value: 42
    
    # 使用 repr() 输出
    print(repr(example_obj))  # 输出: Example(42)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

      官网示例
    在这里插入图片描述

    2.1 格式化字符串字面量

      格式化字符串字面值 (简称为f-字符串)在字符串前加前缀fF,通过 {expression} 表达式,把 Python 表达式的值添加到字符串内。
    基本语法:

    variable1 = "value1"
    variable2 = "value2"
    formatted_string = f"Text {variable1}, more text {variable2}."
    
    • 1
    • 2
    • 3

      格式说明符是可选的,写在表达式后面,可以更好地控制格式化值的方式。
      f-string 提供了一种直观、简洁且强大的字符串格式化方式,适用于许多场景:

    2.1.1 插入变量值

    """
        输出: “姓名: Scott, 年龄: 30”
    """
    name = "Scott"
    age = 30
    print(f"姓名: {name}, 年龄: {age}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.1.2 表达式计算

    """
        输出: “The sum of 5 and 10 is 15.”
    """
    x = 5
    y = 10
    print(f"The sum of {x} and {y} is {x + y}.")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.1.3 对齐和宽度控制

      使用 <,>,^控制文本的左对齐、右对齐和居中,以及指定字段的宽度。

    """
        输出: “姓名: Bob        年龄: 25”
    """
    name = "Bob"
    age = 25
    print(f"姓名: {name:<10} 年龄: {age}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.1.4 格式规范

    """
        输出: 
        “The value of pi is approximately 3.1416 .”
        "小数点后保留3位:9.143"
    """
    import math
    print(f'The value of pi is approximately {math.pi:.4f} .')
    
    number_f = 9.14298078
    print(f'小数点后保留3位:{number_f:.3f}')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.1.5 调用函数

    """
        输出:“Uppercase: HELLO WORLD!”
    """
    print(f"Uppercase: {'hello world!'.upper()}")
    
    • 1
    • 2
    • 3
    • 4

    2.1.6 使用字典和列表

    """
        输出:
        “姓名: Charlie, 年龄: 22”
        “我喜欢水果: apple, orange”
    """
    # 使用字典
    person = {'name': 'Charlie', 'age': 22}
    print(f"姓名: {person['name']}, 年龄: {person['age']}")
    
    # 使用列表
    fruits = ['apple', 'banana', 'orange']
    print(f"我喜欢水果: {fruits[0]}, {fruits[2]}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.1.7 内嵌if语句

    """
        输出:“你可以购买酒类商品。”
    """
    is_adult = True
    print(f"你{'可以' if is_adult else '不可以'}购买酒类商品。")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.1.8 转义字符

      可以使用{{ }} 来插入花括号字符,而不是作为f-string 的开始和结束。

    """
        输出:“值为: 42%, 而不是 {value}”
    """
    value = 42
    print(f"值为: {value}%, 而不是 {{value}}")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2 字符串 format() 方法

      str.format() 方法是Python中用于格式化字符串的一种方式。它允许你创建带有占位符的字符串,然后使用传递给format() 方法的参数替换这些占位符。这种方法使得字符串的格式更加清晰和灵活。
      基本语法:
      {} 是一个占位符,它将在运行时由format() 方法中提供的值替换。可以使用多个占位符,并按照顺序提供相应数量的值。

    formatted_string = "Hello, {}!".format(value)
    
    • 1

    2.2.1 按位置访问参数

    print('{0}, {1}, {2}'.format('a', 'b', 'c')) # 输出 a, b, c
    print('{}, {}, {}'.format('a', 'b', 'c') ) # 输出 a, b, c
    print('{2}, {1}, {0}'.format('a', 'b', 'c')) # 输出 c, b, a
    print('{2}, {1}, {0}'.format(*'abc') ) # 输出 c, b, a
    print('{0}{1}{0}'.format('abra', 'cad') ) # 输出 abracadabra
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2.2 按名称访问参数

      输出:‘Coordinates: 37.24N, -115.81W’

    coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
    'Coordinates: {latitude}, {longitude}'.format(**coord)
    
    • 1
    • 2
    'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
    
    • 1

    2.2.3 访问参数的属性

    c = 3-5j
    ('The complex number {0} is formed from the real part {0.real} '
     'and the imaginary part {0.imag}.').format(c)
    
    class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
        def __str__(self):
            return 'Point({self.x}, {self.y})'.format(self=self)
    
    str(Point(4, 2))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.2.4 访问参数项

    coord = (3, 5)
    'X: {0[0]};  Y: {0[1]}'.format(coord) # 输出 'X: 3;  Y: 5'
    
    • 1
    • 2

    2.2.5 对齐文本并指定宽度

    """
    输出 :
        "left aligned                  "
        "                 right aligned"
        "           centered           "
        "***********centered***********"
    """
    print('{:<30}'.format('left aligned')) 
    print('{:>30}'.format('right aligned')) 
    print('{:^30}'.format('centered'))
    # use '*' as a fill char
    print('{:*^30}'.format('centered') )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.2.6 Replacing , , and and specifying a sign:%+f%-f% f

    """
    输出
        "+3.140000; -3.140000"
        " 3.140000; -3.140000"
        "3.140000; -3.140000"
    """
    # show it always
    print('{:+f}; {:+f}'.format(3.14, -3.14))
    # show a space for positive numbers
    print('{: f}; {: f}'.format(3.14, -3.14))  
    # show only the minus -- same as '{:f}; {:f}'
    print('{:-f}; {:-f}'.format(3.14, -3.14))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.2.7 进制转换

    """
    输出
       "int: 42;  hex: 2a;  oct: 52;  bin: 101010"
       "int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010" 
    """
    # format also supports binary numbers
    print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42))
    
    # with 0x, 0o, or 0b as prefix:
    print("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.2.8 使用逗号作为千位分隔符

    print('{:,}'.format(1234567890)) # 输出 “1,234,567,890”
    
    • 1

    2.2.9 表示百分比

    points = 19
    total = 22
    
    # 输出带2位小数的百分数:Correct answers: 86.36%
    print('Correct answers: {:.2%}'.format(points/total)) 
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2.10 使用特性类型的格式(如时间格式)

    import datetime
    d = datetime.datetime(2010, 7, 4, 12, 15, 58)
    '{:%Y-%m-%d %H:%M:%S}'.format(d) # 输出 '2010-07-04 12:15:58'
    
    • 1
    • 2
    • 3

    2.2.11 嵌套参数

    for align, text in zip('<^>', ['left', 'center', 'right']):
        print('{0:{fill}{align}16}'.format(text, fill=align, align=align))
    
    • 1
    • 2

    运行结果:
    在这里插入图片描述

    octets = [192, 168, 0, 1]
    formatted_string = '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
    print(formatted_string)  # 转换为8进制:C0A80001
    int(formatted_string,16) # 转换为10进制 3232235521
    
    • 1
    • 2
    • 3
    • 4
    # 将5-11的十进制、八进制、十六进制、二进制列出来
    width = 5
    for num in range(5,12): 
        for base in 'dXob':
            print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
        print()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

      运行结果:
    在这里插入图片描述

    2.3 手动格式化字符串

    2.3.1 手动格式化实现同一个平方和立方的列表

      字符串对象的 str.rjust() 方法通过在左侧填充空格,对给定宽度字段中的字符串进行右对齐。同类方法还有str.ljust() str.center() 。这些方法不写入任何内容,只返回一个新字符串,如果输入的字符串太长,它们不会截断字符串,而是原样返回;虽然这种方式会弄乱列布局,但也比另一种方法好,后者在显示值时可能不准确(如果真的想截断字符串,可以使用 x.ljust(n)[:n] 这样的切片操作 。)

    for x in range(1, 11):
        print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
        # Note use of 'end' on previous line
        print(repr(x*x*x).rjust(4))
    
    • 1
    • 2
    • 3
    • 4

    运行结果:
    在这里插入图片描述

    2.3.2 str.zfill()

      该方法在数字字符串左边填充零,且能识别正负号:

    print('12'.zfill(5)) # 输出 00012
    print('-3.14'.zfill(7)) # 输出 -003.14
    print('3.14159265359'.zfill(5)) # 输出 3.14159265359
    
    • 1
    • 2
    • 3

    2.4 旧式字符串格式化方法

      %运算符(求余符)也可用于字符串格式化。给定'string' % values,则string 中的% 实例会以零个或多个values元素替换。此操作被称为字符串插值。例如:

    # 输出 The value of pi is approximately 3.142.
    import math
    print('The value of pi is approximately %5.3f.' % math.pi)
    
    • 1
    • 2
    • 3

    3. 读写文件

      见下一个博客内容。
    在这里插入图片描述

  • 相关阅读:
    ES6 扩展运算符 ...【详解】(含使用场景、实战技巧和范例、实现原理、错误用法)
    消息队列RabbitMQ的常见面试题目
    Flutter 启动白屏
    盘点国产ChatGPT十大模型
    Informer学习记录之Informer-Tensorflow版本
    Java基础 : BlockingQueue浅析
    Java中JVM的xmx和xms配置成一样的好处
    python+django网吧会员管理系统
    DPDK系列之三十一DPDK的并行机制简介
    树莓派4B(Ubuntu 22.04 server)与Windows11网线直连(无显示器)
  • 原文地址:https://blog.csdn.net/Snailandfish/article/details/134469578