MacPython
MacPython

Reputation: 18271

string formatting django

How can I access multiple variables at different positions? How does %s have to look like at inseration point and how at the end to correctly insert the variables.

Thanks!

Here is the code:

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)

Upvotes: 4

Views: 10715

Answers (2)

Alvaro Rodriguez Scelza
Alvaro Rodriguez Scelza

Reputation: 4174

A better, more modern approach might be that of https://www.w3schools.com/python/ref_string_format.asp

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

or better yet:

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)

Upvotes: 1

second
second

Reputation: 28637

not sure what you are asking. do you just want to insert multiple values in your string?

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

Upvotes: 6

Related Questions