3

Python基础之输入、输出、转义、结束符

 1 year ago
source link: https://blog.51cto.com/u_13236892/5856798
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python基础之输入、输出、转义、结束符

精选 原创

哭泣的馒头 2022-11-16 16:58:03 博主文章分类:python基础 ©著作权

文章标签 进制 字符串 左对齐 文章分类 Linux 系统/运维 yyds干货盘点 阅读数156

1、输入的语法
input("提示信息")

2、输入的特点
当程序执⾏到 input ,等待⽤户输⼊,输⼊完成之后才继续向下执⾏。
在Python中, input 接收⽤户输⼊后,⼀般存储到变量,⽅便使⽤。
在Python中, input 会把接收到的任意⽤户输⼊的数据都当做字符串处理。

3、示例
password = input('请输⼊您的密码:')
print(f'您输⼊的密码是{password}')
# <class 'str'>
print(type(password))

4、总结
输⼊功能
input('提示⽂字')
输⼊的特点
⼀般将input接收的数据存储到变量
input接收的任何数据默认都是字符串数据类型

二、格式化输出

1、格式化符号

1、格式符号
格式符号 转换
%s 字符串
%d 有符号的⼗进制整数
%f 浮点数
%c 字符
%u ⽆符号⼗进制整数
%o ⼋进制整数
%x ⼗六进制整数(⼩写ox)
%X ⼗六进制整数(⼤写OX)
%e 科学计数法(⼩写'e')
%E 科学计数法(⼤写'E')
%g %f和%e的简写
%G %f和%E的简写

重点
%s 字符串
%d 有符号的⼗进制整数
%f 浮点数
技巧
%06d,表示输出的整数显示位数,不⾜以0补全,超出当前位数则原样输出
%.2f,表示⼩数点后显示的⼩数位数。

2、输出
age=18
name='qingchen'
weight=75.5
sno=9
#我的名字是qingchen
print('我的名字是%s' % name)
#我的学号是0009
print('我的学号是%04d' % sno)
#我的体重是75.50公斤
print('我的体重是%.2f公斤' % weight)
#我的名字是qingchen,今年18岁
print('我的名字是%s,今年%d岁' % (name,age))

2、格式化format

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
使用方法由两种:b.format(a)和format(a,b)。

1、基本用法
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”
>>> print('{} {}'.format('hello','world')) # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
world hello world

2、进阶用法
(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
(2)取位数“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('hello','world')) # 默认左对齐
hello and world
>>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
hello and world
>>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
hello and world
>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
1.123 is 1.12

3、格式化字符串

Python输出函数print加上 f 的作用:即print(f" ")
主要作用就是格式化字符串,加f后可以在字符串里面使用用花括号括起来的变量和表达式
包含的{}表达式在程序运行时会被表达式的值代替。
#使用f打印
print(f'我的名字是{name},明年{age + 1}岁')
f-格式化字符串是Python3.6中新增的格式化⽅法,该⽅法更简单易读。

三、转义字符

\n :换⾏。
\t :制表符,⼀个tab键(4个空格)的距离。

四、结束符

想⼀想,为什么两个print会换⾏输出?
1 print('输出的内容', end="\n")
在Python中,print(), 默认⾃带 end="\n" 这个换⾏结束符,所以导致每两个 print 直接会换⾏
展示,⽤户可以按需求更改结束符。
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK