您好,欢迎访问一九零五行业门户网

Python中的字符串格式化方式:format()函数的使用方法

变量插入字符串的方法python中的format()函数是一种将变量插入字符串的方法,能够使字符串更易于阅读和理解。它支持许多不同的用法,以下是具体的用法和说明:
使用位置参数传递变量
name = 'john'age = 25print('my name is {}, and i am {} years old.'.format(name, age))# 输出:my name is john, and i am 25 years old.
使用索引传递变量
name = 'john'age = 25print('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 = 25print('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.99print('the price is ${:.2f}'.format(price))# 输出:the price is $19.99
对齐文本
text = 'hello'print('{:>10}'.format(text)) # 右对齐输出,总宽度为10# 输出: helloprint('{:^10}'.format(text)) # 居中输出,总宽度为10# 输出: hello print('{:<10}'.format(text)) # 左对齐输出,总宽度为10# 输出:hello
使用格式化字符串(python 3.6及以上版本)
name = 'john'age = 25print(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 = 95print('student: {0:&lt;10} score: {1:.2f}'.format(name, score))# 输出:student: john score: 95.00
根据变量类型自动选择格式
x = 42y = 3.14print('x is {!r}, y is {!s}'.format(x, y))# 输出:x is 42, y is 3.14
使用填充字符
x = 42print('{:0&gt;5}'.format(x)) # 右对齐,用 0 填充,总宽度为 5# 输出:00042
根据变量类型选择不同的进制输出
x = 42print('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.00print(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中的字符串格式化方式:format()函数的使用方法的详细内容。
其它类似信息

推荐信息