8

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!

3
  • why someone marked it off-topic!!?? Commented Jan 29, 2014 at 18:01
  • @GrijeshChauhan there's no telling. But while I think this is a good question, it has nothing to do with the matplotlib library. So the problem could be trimmed down significantly and the matplotlib tag removed in the OP were so inclined. Commented Jan 29, 2014 at 18:22
  • @PaulH yes you are correct, I like this question because I didn't know this difference between Python2.X and 3.X Commented Jan 29, 2014 at 18:33

2 Answers 2

7

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"
Sign up to request clarification or add additional context in comments.

2 Comments

@Bakuriu Didn't know that, just tried that on Python 3.3 but it doesn't seem to work with ur.
Uhm. seems like the backported the u prefix but not ur... pretty strange.
6

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)

2 Comments

so, i have got a new error if I put this change python3 funcion_pol2.py File "funcion_pol2.py", line 14 rcParams['text.latex.preamble'] = '\usepackage{amsthm}', '\usepackage{amsmath}', '\usepackage{amssymb}', ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
ok i've mended the error using '\\usepackage{amsthm}' opposite to '\usepackage{amsthm}'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.