100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Python基础 | 字符串格式化输出及print()函数介绍

Python基础 | 字符串格式化输出及print()函数介绍

时间:2023-11-18 17:12:03

相关推荐

Python基础 | 字符串格式化输出及print()函数介绍

在写代码时,我们会经常与字符串打交道,Python中控制字符串格式通常有三种形式,分别是使用str%,str.format(),f-str,用法都差不多,但又有一些差别。

一起来看看吧~~~

一、%用法

1、字符串输出

>>>print('hi! %s!'%('Echohye')) # 如果只有一个数,%后面可以不加括号,如print('hi! %s!'%'Echohye'),下同hi! Echohye!>>> name = 'Echohye'>>> print('hi! %s'%(name)hi! Echohye>>> id = '123'>>> print('%s的id是%s'%(name,id))Echohye的id是123

2、整数输出

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

>>> print('今年%d岁了'%(20))今年20岁了

3、浮点数输出

%f ——保留小数点后面六位有效数字

%.2f,保留2位小数

>>> print('%f'%1.2345)1.234500>>> print('%.2f'%1.2345)1.23

%e ——保留小数点后面六位有效数字,指数形式输出

%.2e,保留2位小数位,使用科学计数法

>>> print('%e'%1.11111)1.111110e+00>>> print('%.2e'%1.11111)1.11e+00

%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法

%.2g,保留2位有效数字,使用小数或科学计数法

>>> print('%g'%1.2345678)1.23457>>> print('%.2g'%1.2345678)1.2

4、占位符宽度输出

%20s——右对齐,占位符10位%-20s——左对齐,占位符10位%.3s——截取3位字符%20.3s——20位占位符,截取3位字符%-10s%10s——左10位占位符,右10位占位符

小结:小数点前是正数,则右对齐;小数点前是负数,则左对齐;小数点后面是多少则截取多少位

格式符

格式符为真实值预留位置,并控制显示的格式。格式符可以包含有一个类型码,用以控制显示的类型,如下:

%s 字符串 (采用str()的显示)

%r 字符串 (采用repr()的显示)

%c 单个字符

%b 二进制整数

%d 十进制整数

%i 十进制整数

%o 八进制整数

%x 十六进制整数

%e 指数 (基底写为e)

%E 指数 (基底写为E)

%f 浮点数

%F 浮点数,与上相同

%g 指数(e)或浮点数 (根据显示长度)

%G 指数(E)或浮点数 (根据显示长度)

>>> print('%20s'%('hi! Echohye'))hi! Echohye>>> print('%-20s'%('hi! Echohye'))hi! Echohye>>> print('%.3s'%('hi! Echohye'))hi!>>> print('%20.3s'%('hi! Echohye'))hi!>>> print('%-10s%10s'%('hi! ','Echohye'))hi!Echohye另外注意下面这种情况>>> print('%5d'%3)3>>> print('%05d'%3)00003>>> print('%05s'%'3')3

二、str.format()用法

官方文档介绍:

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

下面我们一起研究看看吧

1、字符串输出

>>>"{} {}!".format("hello", "Echohye") # 不设置指定位置,按默认顺序'hello Echohye!'>>> "{0} {1}!".format("hello", "Echohye") # 设置指定位置'hello Echohye!'>>> "{1} {0}!".format("hello", "world") # 设置指定位置'Echohye hello!'

设置带参数:

# 通过字典设置参数site = {"name": "Echohye", "wxNum": "Echo_hyee"}print("名字:{name}, 微信号:{wxNum}".format(**site)) #**不能落下# 通过列表索引设置参数list = ['Echohye', 'Echo_hyee']print("名字:{0[0]}, wxNum:{0[1]}".format(list)) #“0”不能落下#那下面这样子呢>>> list = [['Echohye', 'Echo_hyee'],['小二', '12345']]>>> print("名字:{0[0]}, wxNum:{0[1]}".format(list))名字:['Echohye', 'Echo_hyee'], wxNum:['小二', '12345']>>> print("名字:{0[1][0]}, wxNum:{0[1][1]}".format(list))名字:小二, wxNum:12345>>> print("名字:{0[0]}, wxNum:{0[1]}".format(list[0]))名字:Echohye, wxNum:Echo_hyee

我只能说灵活运用哈

2、整数输出

>>> print('{}'.format(1314))1314>>>print('{:.0f}'.format(1314.22)1314#这里不过多介绍了,个人感觉用法跟前面字符串输出的差不多

3、浮点数输出

# 保留小数后两位>>>print('{:.2f}'.format(3.1415926))3.14# 带符号保留小数后两位,+ 表示在正数前显示 +,在负数前显示 ->>>print('{:+.2f}'.format(3.1415926))+3.14>>> print('{:+.2f}'.format(-3.1415926))-3.14# 不带小数>>>print('{:.0f}'.format(3.1415926)) # “0”不能省3

4、占位符宽度输出

# 空格补x,填充左边,宽度为10>>>print('{:x>10s}'.format('happy'))xxxxxhappy# 空格补x,填充右边,宽度为10>>>print('{:x<10s}'.format('happy'))happyxxxxx# 空格补x,填充两边,宽度为10>>> print('{:x^10s}'.format('happy'))xxhappyxxx # 如果占位符数是奇数,则右边多于左边# 说明:x只能是指定一个字符,不可以多位,可以是任何字符,默认为空格>>> print('{:>10s}'.format('happy'))happy>>> print('{:&>10s}'.format('happy'))&&&&&happy>>> print('{:`>10s}'.format('happy'))`````happy>>> print('{:.>10s}'.format('happy')).....happy>>> print('{:/>10s}'.format('happy'))/////happy>>> print('{:a>10s}'.format('happy'))aaaaahappy>>> print('{:2>10s}'.format('happy'))22222happy

5、其它格式

# 以逗号分隔的数字格式>>> print('{:,}'.format(999999999))999,999,999# 百分比格式>>> print('{:%}'.format(0.99999)) # 默认仍是六位小数99.999000%>>> print('{:.2%}'.format(0.99999))100.00%>>> print('{:.2%}'.format(0.9999))99.99%# 指数记法>>> print('{:.0e}'.format(1000000))1e+06>>> print('{:.2e}'.format(1000000))1.00e+06>>> print('{:.2e}'.format(0.1000000))1.00e-01>>> print('{:.2e}'.format(0.000001))1.00e-06

注:本处参考’菜鸟教程’

三、f-str用法

f-str的用法,其实跟str.format()的用法差不多,不过我跟喜欢用f-str,因为它更加简洁、方便、高效。

1、字符串输出

# 字符串输入>>> print(f"my name is {'Echohye'},nice to meet you!") # 这里得注意""和''的嵌套了my name is Echohye,nice to meet you!# 参数代入>>> name = 'Echohye'>>> print(f'my name is {name},nice to meet you!')my name is Echohye,nice to meet you!# 字符串截取>>> name = 'Echohye'>>> print(f"my name is {'Echohye':.3s},nice to meet you!")my name is Ech,nice to meet you!>>> print(f"my name is {name:.3s},nice to meet you!")my name is Ech,nice to meet you!# 有没有觉得很方便快捷?haha,当然,这个Python2是不支持的哟~

2、整数输出

>>> print(f'{1314}')1314>>> num = 1314>>> print(f'{num}')1314

3、浮点数输出

4、占位符宽度输出

用法跟str.format()的基本一样,如果想继续挖掘就参考前面的哈,我就不过多赘述了。目前我觉得二者区别就是把str.format()里()括号的内容放到了f’{:}'的:前面。当然,不一样的地方可能也有,只是我还未遇到,靠大家一起来探索啦

四、讨论一下print()函数

print() 方法用于打印输出,是python中最常见的一个函数。

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

下面是print()的参数介绍

>>> help(print)Help on built-in function print in module builtins:print(...)print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default.Optional keyword arguments:file: a file-like object (stream); defaults to the current sys.stdout.sep: string inserted between values, default a space.end: string appended after the last value, default a newline.flush: whether to forcibly flush the stream.

参数的具体含义如下:

value --表示输出的对象。输出多个对象时,需要用 , (逗号)分隔。

可选关键字参数:

file – 要写入的文件对象。

sep – 用来间隔多个对象。

end – 用来设定以什么结尾。默认值是换行符 \n,可以换成其他字符。

flush – 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。

例子介绍:

value参数

>>> print('Echo','hye')Echo hye>>> print('Echo''hye')Echohye>>> print(1300,'+',14,'=',1300+14) #这个不错,乱套也是行的haha1300 + 14 = 1314# 第二个其实还有个用处,比如你码了一行很长的代码,电脑屏幕都不够显示,我们这是就可以用print("""")打断,但其实还是连着一起的。>>> print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa''cccccccccccccccccccccc')aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccc# 我其实想在中间按个回车的,可IDLE Shell不能直接回车~~~但我们在py文件里面下还是可以的^_^file参数

(略…)

sep参数

>>> print('Echo','hye',sep='?')Echo?hye# 试下把字符串间的逗号去掉,就不行了>>> print('Echo''hye',sep='?')Echohye>>> print('Echo','hye',sep=' ~我裂开了~ ')Echo ~我裂开了~ hye>>> print('Echo','hye',sep='\n')Echohye>>> print('Echo','hye',sep='\t')Echo hye>>> print('Echo','hye',sep='\n\t')Echohye# 小结:sep=''里的字符,就是替换掉逗号的,而且不局限于一个字符,可以是一个字符串,也可以是转义字符,专业字符还能组队出场 ->(ΩДΩ)震惊~~~# 是我孤陋寡闻了o(╥﹏╥)o

end参数

猜想:前面的sep参数是作用在中间的逗号,end参数是作用在结尾,而默认的是’\n’,如果设其它参数,也就相当于替换掉’\n’,那用法应该也是一致的。下面实践看看

>>> print('Echo','hye',end='\nhere')Echo hyehere>>> print('Echo','hye',end='\there')Echo hye here>>> print('Echo','hye',end='\n\there')Echo hyehere# 实践出真知,确实如此,end参数的用法跟sep参数的用法基本一样flush参数# 在PyCharm里执行import timeprint("Loading", end="")for i in range(10):print(".", end='', flush=True)time.sleep(0.5)print()print("Loading", end="")for i in range(10):print(".", end='', flush=False)time.sleep(0.5)#结果Loading..........Loading..........

我没看出来有什么区别,可能用处不是在这,只是我还没发现 &umum~

print()函数用法就介绍到这里咯,有兴趣的小伙伴可以继续深入了解哈~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。