Concerned_Citizen
Concerned_Citizen

Reputation: 6835

Constructing String Without Concatenation in Python 2.7

Is there any way to place a declared string in between unicode symbols without concatenation? For example, I have declared a string a = "house". Is there anyway I can declare <\house/> without having to result to "<\\" + a + "/>" ? Concatenation may become cumbersome when more unicode symbols get involved.

Upvotes: 0

Views: 83

Answers (2)

Salem
Salem

Reputation: 12986

You can use the str.format method:

a = "Hello {name}, welcome to {place}."
a.format(name="Salem", place="Tokyo")  # "Hello Salem, welcome to Tokyo."

docs.python.org - String format syntax

If you need something more powerful, you can use a template engine. There is a quick example with Jinja2:

  • jinja_example.py

    from jinja2 import Template
    
    template_file = Template(open("templatefile").read())
    
    obj = [
        {"name": "John", "surname": "Doe"},
        {"name": "Foo", "surname": "Bar"}
    ]
    
    print template_file.render(data=obj)
    
  • templatefile

    <html>
    <body>
    {% if data %}
        {% for user in data %}
        <h1>Hello {{ user.name }} {{ user.surname }}.</h1>
        {% endfor %}
    {% else %}
        <h1>Nothing found.</h1>
    {% endif %}
    </body>
    </html>
    

And the output (some newline's removed):

$ python jinja_example.py
<html>
<body>
    <h1>Hello John Doe.</h1>    
    <h1>Hello Foo Bar.</h1> 
</body>
</html>

You can find a huge list of template engines in Python Wiki.

Upvotes: 2

Erik Kaplun
Erik Kaplun

Reputation: 38217

how about string interpolation?

"<\\%s/>" % a

or for multiple items:

<"\\%s %s/>" % (a, b)

Also works with dictionaries:

"<\\%(a)s/>" % {'a': a}

Python 3.x style interpolation is done using the built in str.format method:

"<\\{}/>".format(a)
"<\\{} {}/>".format(a, b)
"<\\{1} {0}/>".format(a, b)  # => "<\\" + b + " " + a + "/>"
"<\\{a} {b}/>".format(a=a, b=b)

Upvotes: 2

Related Questions