简体   繁体   中英

Invalid syntax error using format with a string in Python 3 and Matplotlib

The code:

#/usr/bin/env python3
# -*- coding: utf-8 -*-


import numpy as np
import matplotlib.pyplot as plt
from sympy.solvers import *
from sympy import *
from matplotlib import rcParams


rcParams['text.latex.unicode'] = True
rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = '\usepackage{amsthm}', '\usepackage{amsmath}', '\usepackage{amssymb}',
'\usepackage{amsfonts}', '\usepackage[T1]{fontenc}', '\usepackage[utf8]{inputenc}'


f = lambda x: x ** 2 + 1
#f = lambda x: np.sin(x) / x

x = Symbol('x')
solucion = solve(x**2+1, x)

fig, ax = plt.subplots()
x = np.linspace(-6.0, 6.0, 1000)
ax.axis([x[0] - 0.5, x[-1] + 0.5, x[0] - 0.5, x[-1] + 0.5])
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top']
ax.spines['left']
ax.spines['bottom']
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.grid('on')
ticks = []
for i in range(int(x[0]), int(x[-1] + 1), 1):
    ticks.append(i)
ticks.remove(0)
ax.set_xticks(ticks)
ax.set_yticks(ticks)

ax.plot(x, f(x), 'b-', lw=1.5)
ax.legend([r'$f(x)=x^2-1$'], loc='lower right')

text_sol = ''
if solucion == []:
    text_sol = r'$No\; hay\; soluciones $'
else:
    for i, value in enumerate(solucion):
        text_sol += ur'$Solución \; {}\; :\; {}\\$'.format(i, value)

bbox_props = dict(boxstyle='round', fc='white', ec='black', lw=2)
t = ax.text(-5.5, -5, text_sol, ha='left', va='center', size=15,
            bbox=bbox_props)

plt.show()

This code works fine with Python 2.7 but with Python 3.3.2 is bad:

python3 funcion_pol2.py
  File "funcion_pol2.py", line 51
    text_sol += ur'$Solución \; {}\; :\; {}\\$'.format(i, value)
                                               ^
SyntaxError: invalid syntax

Thanks!

The u'...' syntax for string literal was removed in Python 3.0

From docs :

String literals no longer support a leading u or U .

So, you can simply drop the u'...' in Python 3:

r'$Solución \; {}\; :\; {}\\$'.format(i, value)

Note: The u'...' syntax has been re-introduced in Python 3.3 (thanks to @Bakuriu for pointing that out).

And the new re-introduced string-prefix syntax looks like this:

stringprefix    ::=  "r" | "u" | "R" | "U"

Python 2 string-prefix syntax :

stringprefix    ::=  "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"
                     | "b" | "B" | "br" | "Br" | "bR" | "BR"

Since you are using Python 3.3, the problem is not that you have a u before the string literal. Instead, the problem is that you are placing ur before it:

>>> # Python 3.3.2 interpreter
>>> u'a'
'a'
>>> ur'a'
  File "<stdin>", line 1
    ur'a'
        ^
SyntaxError: invalid syntax
>>>

This behavior is explained in the docs :

Given that Python 2.x's raw unicode literals behave differently than Python 3.x's the 'ur' syntax is not supported.

...

New in version 3.3: Support for the unicode legacy literal (u'value') was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.


Since all strings in Python 3.x are unicode, you can fix the problem by simply removing the u :

r'$Solución \; {}\; :\; {}\\$'.format(i, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM