Format string with single quotes in it
joncle at googlemail.com
Fri Sep 25 15:36:24 CEST 2009
On 25 Sep, 13:42, Bahadir <bilgehan.bal... at gmail.com> wrote:
> 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)
Don't call variables 'str' as it'll mask the builtin string type.
> I get the error:
> ValueError: unsupported format character '
> ' (0xa) at index 5541
Index 5541!? I would guess the lines in the file aren't quite what you
think. The message you're receiving suggests you've got a % character,
followed by a linefeed character -- are you opening the file in text
mode, if not, do so... and if your file has mixed newline sequences,
try using the universal newline option: infile = open
> I also tried:
> # Replace single quotes with \'
> str = str.replace("'", "\'")
> and doubling the backward slash as well.
None of that is needed AFAICT.
> What am I doing wrong?
> Thank you,
jon at jon-desktop:~$ cat test.txt
line 1 SOMELINE%d and some value of %d
line 2 SOMELINE%d and some value of %d
line 3 SOMELINE%d and some value of %d
line 4 SOMELINE%d and some value of %d
jon at jon-desktop:~$ cat test.py
for line in open('test.txt'):
print line.rstrip('\n') % (0, 0)
jon at jon-desktop:~$ python test.py
line 1 SOMELINE0 and some value of 0
line 2 SOMELINE0 and some value of 0
line 3 SOMELINE0 and some value of 0
line 4 SOMELINE0 and some value of 0
More information about the Python-list