首页 > 解决方案 > 实际上我想对 f 字符串中的文本使用标题方法?

问题描述

     my_favourites=['lamborghini',"sea facing resort",
            '100 b dollar','3D animator']
     line_1='and by that much money i want to own a '.title()+my_favourites[1].title()+' & a 
            '+my_favourites[0].upper()
     print(line_1)
     line_2=f'and by that much money i want to own a {my_favourites[1].title()} & a 
     {my_favourites[0].upper()}'
     print(line-2)

#所以这里的问题是连接效果很好,但我不知道如何将标题方法应用于 f-string 语法中的初始文本,而不将该文本分配给额外的变量。

标签: pythonpython-3.xmethodsstring-concatenationf-string

解决方案


我承认 f-strings 有点奇怪:

f"{'and by that much money i want to own a'.title()} {my_favourites[1].title()} & {'a'.title()} {my_favourites[0].upper()}"

str.format我认为在这里会更合适:

"and by that much money i want to own a {} & a {}".title().format(my_favourites[1].title(), my_favourites[0].upper())

推荐阅读