Python 官方文档:入门教程 => 点击学习
变量插入字符串的方法 python中的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:<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>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.
希望这些例子可以帮助您更好地理解format()
函数的用法。
以上就是python学习print中format的用法示例的详细内容,更多关于python print format用法的资料请关注编程网其它相关文章!
--结束END--
本文标题: python学习print中format的用法示例
本文链接: https://www.lsjlt.com/news/201150.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0