0

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.

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

"Python 3.x style" works in 2.6+, so it's not really 3.x style
@Blender: afaik the feature was introduced in and backported to 2.x from 3.x.
2

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.

1 Comment

Python uses '#' for comments instead of '//' .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.