【python语法】print格式化输出及输出内容到文件中

python几种print输出方式及输出到文件中的方法

一、基础输出

  1. 输出一句话

    print("hello world.")
    '''
    return:
    hello world.
    '''
    
  2. 输出变量&字符串
    逗号分隔开变量与字符串。其中变量和字符串中间会自动加入空格

    name = "Kang"
    fruit = "apple"
    print("I'm", name, ", I like ", fruit)
    '''
    return:
    I'm Kang , I like apple
    '''
    

    或用加号将变量转换为字符串类型与给定字符串拼接,字符串中间没有空格

    name = "Kang"
    age = 12
    print("My name is " + name + ", I'm " + str(age) + " years old.")
    '''
    return:
    My name is Kang, I'm 12 years old.
    '''
    

二、格式化输出

  1. %占位符

    几个常用的占位符:
    %s-为字符串占位
    %d-为整数占位
    %f-为浮点数占位(默认6位)
    %.nf-%f也可以对输出浮点数的位数进行规定,语法为%.nf,n为你想保留的小数点后n位数。
    语法为:print("I'm %s" % string)

    name = "Kang"
    age = 15
    height = 1.8746
    print("My name is %s, I'm %d years old and My height is %f" %(name, age, height))
    print("My height is about %.2f" % height)
    '''
    return:
    My name is Kang, I'm 15 years old and My height is 1.874600
    My height is about 1.87
    '''
    
  2. format()方法

    format()方法的使用对象是一个字符串,字符串中需要用到{ }作为占位符
    format()方法中的变量值会依次填入到字符串中的{ }中。
    但是此时,如果您需要在字符串中打印==花括号“{ }”==的话,您需要加倍打印{{ }}即可避免format()方法在您想打印的花括号上进行数据的填充。
    format()方法也可以用%.nf的方法格式化浮点数位数,但是在.nf前需要加”:",记作:.nf

    name = "Kang"
    height = 1.8746
    print("My name is {}, My height is {}.".format(name, height))
    print("My height{{}} is about {:.2f}.".format(height))
    '''
    return:
    My name is Kang, My height is 1.8746.
    My height{} is about 1.87.
    '''
    

    补充,附一张图在这里插入图片描述

  3. f-string构建字符串

    在要输出的字符串外加一个字符f,再在字符串中加入{变量},即可将变量值嵌入字符串中。
    这种方法最简单
    语法为 print(f"some string {value}")
    和format()方法相同,f-string方法也可以用%.nf的方法格式化浮点数位数,但是在.nf前需要加":",记作:.nf

    name = "Kang"
    age = 15
    height = 1.8746
    print(f"My name is {name}, I'm {age} years old and My height is {height}")
    print("My height is about {height:.2f}")
    '''
    return:
    My name is Kang, I'm 15 years old and My height is 1.874600
    My height is about 1.87
    '''
    
  4. 控制换行

    print输出时,可以使用end参数来控制是否换行。

    print("第一行", end=" ")
    print("这不是第二行")
    '''
    return:
    第一行 这不是第二行
    '''
    

三、输出到文件

基础知识
open()函数参数介绍:
file:文件路径(绝对、相对路径);
mode:打开方式,有【r、w、a等】模式;

  • r:只读模式;
  • w:写入模式(原有内容删除);
  • a:追加模式(原有内容保存);

encoding:编码方式。有中文乱码的话,要使用encoding='utf-8'

file = open(r"./test.txt", "w",encoding='utf-8')  # 打开文件
print("这些文字将被写入文件", file=file)  # 输出到文件
file.write("也可以这样写入")

file.close()# 关闭文件

'''
output:
这些文字将被写入文件
也可以这样写
'''

如果要写一些变量的数据到文件中的话,和之前介绍的print格式化输出语法相同。

  • 28
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值