python基础(19)之 输入输出

 

目录

 用户输入

一、格式化输入输出

二、格式化字符串字面值 

三、字符串 format() 方法

四、手动格式化字符串

五、旧式字符串格式化方法


用户输入

 实在太简单了,就是使用一个input(),将输入后的值传递给另一个变量,相当于动态赋值、
例如:

username = input("你叫什么名字:")
print("名字叫: " + username)

返回:

一、格式化输入输出

1.在字符串开头的引号/三引号前添加 f 或 F 。在这种字符串中,可以在 { 和 } 字符之间输入引用的变量
year = 2022
event = 'Referendum'
a=f'Results of the {year} {event}'
print(a)

 返回:

 2.str.format() 该方法也用 { 和 } 标记替换变量的位置a 这种方法支持详细的格式化指令

yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
a='{:-5} YES votes  {:1.1%}'.format(yes_votes, percentage)#调整{}内部感受下
print(a)

 返回:

 如果在这里有的懵,可以试着更改 {} 中的内容,并输出查看结果来进行理解

3.想快速显示变量进行调试,可以用 repr() 或 str() 函数把值转化为字符串

s = 'Hello, world.'
print(str(s))#str() 函数返回供人阅读的值
print(repr(s))#repr() 则生成适于解释器读取的值
print(str(1/7))
hellos = repr('hello')
print(hellos)

返回:

 

二、格式化字符串字面值

格式化字符串字面值 (简称为 f-字符串)在字符串前加前缀 f 或 F,通过 {expression} 表达式,把 Python 表达式的值添加到字符串内
1.下例将 pi 舍入到小数点后三位
import math
print(f'The value of pi is approximately {math.pi:.3f}.')

返回:

 

 2.在 ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10d}')

三、字符串 format() 方法

先看看下面这个例子

print('We are the {} who say "{}!"'.format('knights', 'Ni'))

 返回:

1.花括号及之内的字符(称为格式字段)被替换为传递给 str.format() 方法的对象。花括号中的数字表示传递给 str.format() 方法的对象所在的位置
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))

2.使用关键字参数名引用值

print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))

3.位置参数和关键字参数可以任意组合

print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))

4.用方括号 '[]' 访问键来完成

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))

返回:

 5.也可以用 '**' 符号,把 table 当作传递的关键字参数

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))

四、手动格式化字符串

生成一组整齐的列,包含给定整数及其平方与立方

for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x))

返回:

换种写法如下

for x in range(1, 11):
    print(repr(x).rjust(2), repr(x * x).rjust(3), end=' ')
    print(repr(x * x * x).rjust(4))

五、旧式字符串格式化方法

import math
print('The value of pi is approximately %5.3f.' % math.pi)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值