字符串格式化django

时间:2010-08-04 09:33:31

标签: django

如何在不同位置访问多个变量? %s如何在牺牲点看起来如何以及最后如何正确插入变量。

谢谢!

以下是代码:

from django.http import HttpResponse
from django.contrib.auth.models import User
from favorites.models import *

def main_page_favorites(request):
    title = Favorite.objects.get(id=1).title.upper()
    email = User.objects.get(username='Me').email
    image = Hyperlink.objects.get(id=3).url
    output = '''
        <html>
            <head>
                <title>
                    Connecting to the model
                </title>
            </head>
            <body>
                <h1>
                Connecting to the model
                </h1>
                We will use this model to connect to the model.

                <p>Here is the title of the first favorite: %s</p>

            </body>
        </html>''' % ( title, email, image
        )
    return HttpResponse(output)

2 个答案:

答案 0 :(得分:4)

不确定你在问什么。你只是想在你的字符串中插入多个值吗?

"value 1 is %s, value 2 is %s." % (value1, value2)

答案 1 :(得分:0)

更好、更现代的方法可能是 https://www.w3schools.com/python/ref_string_format.asp

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

或者更好:

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)