Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 708
Tobal Avatar asked Jan 29 '14 17:01

Tobal


1 Answers

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

  • All strings are unicode strings in Python 3.

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"
like image 196
Ashwini Chaudhary Avatar answered Sep 23 '22 01:09

Ashwini Chaudhary