how to string format when string have {

Peter Otten __peter__ at web.de
Mon Apr 21 04:51:06 EDT 2014


Chris Angelico wrote:

> On Mon, Apr 21, 2014 at 8:34 AM, Mariano DAngelo
> <marianoa.dangelo at gmail.com> wrote:
>> And I want to format like this:
>>
>> context = {
>>  "project_name":project_name,
>>  "project_url":project_url,
>>  }
>>
>> nginx_conf.format(**context)
>>
>>
>> but since the string have { i can't.
>> Is there a way to solve this?
> 
> Are you in full control of the source string? You can escape the
> braces as explained here:
> 
> https://docs.python.org/3.4/library/string.html#format-string-syntax
> 
> If you're not in full control (eg if it comes from a user's input), or
> if you don't like the idea of doubling all your braces, you could
> switch to percent-formatting, or some other form of interpolation. But
> the easiest would be to simply escape them.

Some regex gymnastics in the morning (not recommended):

>>> print(nginx_conf)

server {
    listen       80;
    server_name  dev.{project_url};

    location / {
        proxy_pass  http://127.0.0.1:8080;
        include     /etc/nginx/proxy.conf;
    }

    location /media  {
        alias 
/home/mariano/PycharmProjects/{project_name}/{project_name}/media;
        expires 30d;

    }
    location /static  {
        alias 
/home/mariano/PycharmProjects/{project_name}/{project_name}/static;
        expires 30d;
    }

    error_page   500 502  503 504  /50x.html;
    location =  /50x.html {
        root    html;
        }
}
>>> fmt = re.compile(r"((\{)(?!\w)|(?<!\w)(\}))").sub(r"\1\1", nginx_conf)
>>> print(fmt)

server {{
    listen       80;
    server_name  dev.{project_url};

    location / {{
        proxy_pass  http://127.0.0.1:8080;
        include     /etc/nginx/proxy.conf;
    }}

    location /media  {{
        alias 
/home/mariano/PycharmProjects/{project_name}/{project_name}/media;
        expires 30d;

    }}
    location /static  {{
        alias 
/home/mariano/PycharmProjects/{project_name}/{project_name}/static;
        expires 30d;
    }}

    error_page   500 502  503 504  /50x.html;
    location =  /50x.html {{
        root    html;
        }}
}}
>>> print(fmt.format(project_name="MYPROJECT", project_url="MYPROJECT.COM"))

server {
    listen       80;
    server_name  dev.MYPROJECT.COM;

    location / {
        proxy_pass  http://127.0.0.1:8080;
        include     /etc/nginx/proxy.conf;
    }

    location /media  {
        alias /home/mariano/PycharmProjects/MYPROJECT/MYPROJECT/media;
        expires 30d;

    }
    location /static  {
        alias /home/mariano/PycharmProjects/MYPROJECT/MYPROJECT/static;
        expires 30d;
    }

    error_page   500 502  503 504  /50x.html;
    location =  /50x.html {
        root    html;
        }
}





More information about the Python-list mailing list