Python中str.format()和f-string如何使用

作者:有用网 阅读量:95 发布时间:2024-01-17
关键字 python

这篇文章主要介绍“Python中str.format()和f-string如何使用”,在日常操作中,相信很多人在Python中str.format()和f-string如何使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python中str.format()和f-string如何使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

string format 有两种方式:

方式一 (str.format()) :print('{}'.format(var))

1.{} 是占位符 ( placeholder ),对应的值在 format() 的括号内。

例如:

print('Hi, {}!'.format('Mary'))

显示结果为:

Hi, Mary!

2.format() 中可以填入变量,这种方式更常见。例如:

name='Julie'
print('Hi, {}!'.format(name))

显示结果为:

Hi, Julie!

3.还可以有多个变量。例如:

num_apple=6
num_orange=3
print('I bought {} apples and {} oranges.'.format(num_apple,num_orange))

显示结果为:

I bought 6 apples and 3 oranges.

4.{} 可以设置变量格式,前面要加上 :,其后的数字表示这个整数、或字符串、或小数点后有几位。例如:

fruit='apples'
number=6
price=1.2
print('{:5d} {:8}, price:{:.5f}.'.format(number,fruit,price*number))

显示结果为:

6 apples  , price:7.20000.

从结果可以看到:

(1) 比如 apples 有 6 位,设置格式为 8 位 {:8},结果显示中 apples 后面有 2 位空格。

(2) format() 中可以传入变量运算的值,比如例子中的 price*number。

5.{} 中可以加上数字索引,对应的是 format() 中的元素位置。例如:

print('I bought {1} oranges,{0} bananas and {0} apples.'.format(6,3))

显示结果为:

I bought 3 oranges,6 bananas and 6 apples.

上面的语句中,{0} 对应 format(6,3) 的第一个值 6,{1} 对应第二个值 3。

方式二 (f-string) :print(f'{var}')

注:这里既可以用 f'',也可以用 F''。

1.与方式一不同,f'{}'直接在{}写入变量值。例如:

name='Julie'
print(f'{name} is learning Python.')

显示结果为:

Julie is learning Python.

2.与方式一相同,f'' 也可以设置多个变量。例如:

num_apple=6
num_orange=3
print(f'I bought {num_apple} apples and {num_orange} oranges.')

显示结果为:

I bought 6 apples and 3 oranges.

3.与方式一相同,{} 中可以设置格式。例如:

fruit='apples'
number=6
price=1.2
print(f'{number:5d} {fruit:8}, price:{price*number:.5f}')

显示结果为:

6 apples  , price:7.20000


#发表评论
提交评论