在Python中,可以通過嵌套使用format
函數(shù)來實現(xiàn)復雜的格式化輸出。以下是一些嵌套使用format
函數(shù)的技巧:
format
函數(shù)來格式化多個變量:name = 'Alice'
age = 30
address = '123 Main St'
output = 'Name: {0}, Age: {1}, Address: {2}'.format(name, age, address)
print(output)
format
函數(shù)來格式化字典中的值:person = {'name': 'Bob', 'age': 25, 'address': '456 Elm St'}
output = 'Name: {0[name]}, Age: {0[age]}, Address: {0[address]}'.format(person)
print(output)
format
函數(shù)來格式化列表中的值:items = ['apple', 'banana', 'cherry']
output = 'First item: {0[0]}, Second item: {0[1]}, Third item: {0[2]}'.format(items)
print(output)
format
函數(shù)來格式化嵌套的數(shù)據(jù)結(jié)構(gòu):person = {'name': 'Alice', 'age': 30, 'address': {'street': '123 Main St', 'city': 'New York'}}
output = 'Name: {0[name]}, Age: {0[age]}, Address: {0[address][street]}, City: {0[address][city]}'.format(person)
print(output)
通過嵌套使用format
函數(shù),可以輕松地實現(xiàn)復雜的格式化輸出需求。