Python中命名的字符串格式参数

时间:2016-07-25 13:50:43

标签: python python-2.7

我正在使用Python 2.x,并尝试使用命名参数来理解字符串格式的逻辑。我明白了:

"{} and {}".format(10, 20)打印'10 and 20'

以同样的方式'{name} and {state}'.format(name='X', state='Y')打印X and Y

但为什么这不起作用?

my_string = "Hi! My name is {name}. I live in {state}"
my_string.format(name='Xi', state='Xo')
print(my_string)

打印"Hi! My name is {name}. I live in {state}"

1 个答案:

答案 0 :(得分:7)

format不会改变你调用它的字符串;它返回一个新字符串。如果你这样做

my_string = "Hi! My name is {name}. I live in {state}"
new_string = my_string.format(name='Xi', state='Xo')
print(new_string)

然后你应该看到预期的结果。