mehdi
mehdi

Reputation: 1150

how can possible replacing variable value in triple quotation in python/ django with {value}?

i'm noob in django/python ,I saw a code in github about "exporting Vcard" files , my question is about a part that programmer replace variable value in string variable :

admin.py:

output = ""
  for person in queryset.all():
    person_output = """BEGIN:VCARD  
VERSION:3.0
N:{last_name};{first_name}
FN:{first_name} {last_name}
TEL;TYPE=HOME,VOICE:{phone}
TEL;TYPE=WORK,VOICE:{secondary_phone}
EMAIL:{email}
REV:{rev}
END:VCARD"""
    # how can replace value when the source is string?!
    person_output = person_output.format(  
                        first_name = person.first_name, 
                        last_name = person.last_name,
                        phone = person.phone,
                        secondary_phone = person.secondary_phone,
                        email = person.email,
                        rev = d.strftime('%Y%M%d%H%f'),
                        )

can anyone plz explain how it possible and let me know any python/django documentation about it?thank you.

Upvotes: 0

Views: 66

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

This is just simple string formatting [pyformat]. One can specify a string according to the format as is explained in the Python documentation and in PEP-3101 and then by calling my_string.format(..) you replace certain parts in the string with other parts.

The fact that it isa string in between "triple quotation" does not make any difference, since it is just a string.

The entire format is explained in PEP-3101, but in short if you write {var_name} and then you format it with a named argument .format(var_name=value), then {var_name} is replaced by value. There are however some exceptions, for example {{}} is replaced by {}, and the format allows you to align numbers properly, etc.

Since , one can use f-strings [real Python] to perform formatting more effectively.

Upvotes: 1

Related Questions