Format string with single quotes in it

Mark Tolonen metolone+gmane at gmail.com
Fri Sep 25 09:23:23 EDT 2009


"Bahadir" <bilgehan.balban at gmail.com> wrote in message 
news:65b6ce03-62c7-4e56-a746-d85ce87ad840 at l31g2000vbp.googlegroups.com...
> Hi there,
>
> My question is simple, but I've been spending some hours over the web
> and still struggling to get this right: How do I format a string that
> contains single quotes in it?
>
> I am reading a file with lines of the form:
>
> CONT%d_VIRTMEM_REGIONS  'Container %d number of virtual regions'
>
> and trying to format this as follows:
>
> str % (0, 0)
>
> I get the error:
>
> ValueError: unsupported format character '
> ' (0xa) at index 5541
>
> I also tried:
>
> # Replace single quotes with \'
> str = str.replace("'", "\'")
>
> and doubling the backward slash as well.
>
> What am I doing wrong?

A short, working example that exhibits the problem would be helpful, but I 
suspect you have a line in your file that ends in a %.  The code below 
produces the same error.

    s = "Here's a percentage: %d%\n"
    print s % (0,0)

OUTPUT:

    Traceback (most recent call last):
      File 
"C:\dev\python\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", 
line 436, in ImportFile
        my_reload(sys.modules[modName])
      File "w.py", line 2, in <module>
        print s % (0,0)
    ValueError: unsupported format character '
    ' (0xa) at index 24

Inspect your input file.  If you want a percent sign in a format string, use 
%%.

    s = "Here's percentages: %d%% %d%%\n"
    print s % (0,0)

OUTPUT:

    Here's percentages: 0% 0%

-Mark





More information about the Python-list mailing list