python print中的format怎么使用

发布时间:2023-03-25 14:42:09 作者:iii
来源:亿速云 阅读:135

这篇文章主要介绍了python print中的format怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python print中的format怎么使用文章都会有所收获,下面我们一起来看看吧。

变量插入字符串的方法

Python中的format()函数是一种将变量插入字符串的方法,能够使字符串更易于阅读和理解。它支持许多不同的用法,以下是具体的用法和说明:

name = 'John'
age = 25
print('My name is {}, and I am {} years old.'.format(name, age))
# 输出:My name is John, and I am 25 years old.
name = 'John'
age = 25
print('My name is {0}, and I am {1} years old.'.format(name, age))
# 输出:My name is John, and I am 25 years old.
name = 'John'
age = 25
print('My name is {n}, and I am {a} years old.'.format(n=name, a=age))
# 输出:My name is John, and I am 25 years old.
price = 19.99
print('The price is ${:.2f}'.format(price))
# 输出:The price is $19.99
text = 'Hello'
print('{:>10}'.format(text))  # 右对齐输出,总宽度为10
# 输出:     Hello
print('{:^10}'.format(text))  # 居中输出,总宽度为10
# 输出:  Hello   
print('{:<10}'.format(text))  # 左对齐输出,总宽度为10
# 输出:Hello
name = 'John'
age = 25
print(f'My name is {name}, and I am {age} years old.')
# 输出:My name is John, and I am 25 years old.
person = {'name': 'John', 'age': 25}
print('My name is {name}, and I am {age} years old.'.format(**person))
# 输出:My name is John, and I am 25 years old.
fruits = ['apple', 'banana', 'cherry']
print('My favorite fruit is {0[1]}'.format(fruits))
# 输出:My favorite fruit is banana
print('{{Hello}}'.format())  # 输出:{Hello}
name = 'John'
score = 95
print('Student: {0:&lt;10} Score: {1:.2f}'.format(name, score))
# 输出:Student: John       Score: 95.00
x = 42
y = 3.14
print('x is {!r}, y is {!s}'.format(x, y))
# 输出:x is 42, y is 3.14
x = 42
print('{:0&gt;5}'.format(x))  # 右对齐,用 0 填充,总宽度为 5
# 输出:00042
x = 42
print('bin: {0:b}, oct: {0:o}, hex: {0:x}'.format(x))
# 输出:bin: 101010, oct: 52, hex: 2a
def format_salary(salary):
    if salary > 10000:
        return '{:.1f}K'.format(salary / 1000)
    else:
        return '${:,.2f}'.format(salary)
print(format_salary(5000))   # $5,000.00
print(format_salary(15000))  # 15.0K
data = {'name': 'John', 'age': 25}
print('{name} is {age} years old.'.format(**data))  # John is 25 years old.
fruits = ['apple', 'banana', 'cherry']
print('My favorite fruits are {}, {} and {}.'.format(*fruits))  # My favorite fruits are apple, banana and cherry.

关于“python print中的format怎么使用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python print中的format怎么使用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. python中print函数和format函数的使用
  2. python中format方法的使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python print format

上一篇:C++错误使用迭代器超出引用范围问题如何解决

下一篇:Redis阻塞的情况有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》