P11 Custom string formatting

format strings——there are multiple ways that you can do the exact same types of string concatenation.
P12实操
first_name='liu'
last_name='ding yun'
output='hello ' + first_name + ' ' + last_name
output='hello,{}{}'.format(first_name,last_name)
output='hello,{0}{1}'.format(first_name,last_name)
output=f'hello,{first_name} {last_name}'
output='hello,%s %s'%(first_name,last_name)
print(output)
i really like that last string format with the little f at the very beginning there.⬇️ you'll also notice that there's a lot of other programming languages that have a very similar construct. I also really like the fact that it is self-documenting, because i can very clearly see......
first_name='liu'
last_name='ding yun'
# output='hello ' + first_name + ' ' + last_name
# output='hello,{}{}'.format(first_name,last_name)
# output='hello,{0}{1}'.format(first_name,last_name)
output=f'hello,{first_name} {last_name}'
# output='hello,%s %s'%(first_name,last_name)
print(output)
本文探讨了多种字符串格式化方法,包括使用加号连接、format函数、f-string以及百分比符号方法。作者特别提到了f-string的易读性和自文档化特性,并指出这种格式化方式在其他编程语言中也有类似实现。

被折叠的 条评论
为什么被折叠?



