¿Cómo puedo escapar selectivamente el porcentaje ( % ) en cadenas de Python?


Tengo el siguiente código

test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test

print(selectiveEscape)

Me gustaría obtener la salida:

Print percent % in sentence and not have it break.

Lo que realmente sucede:

    selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str
Author: Martin Thoma, 2012-05-21

6 answers

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
 486
Author: Nolen Royalty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-21 00:03:43

Alternativamente, a partir de Python 2.6, puede usar un nuevo formato de cadena (descrito en PEP 3101):

'Print percent % in sentence and not {0}'.format(test)

Que es especialmente útil ya que sus cadenas se vuelven más complicadas.

 49
Author: Karmel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-21 00:12:34

Intente usar %% para imprimir el signo%.

 27
Author: openmeet123,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-22 06:36:07

No puede escapar selectivamente %, ya que % siempre tiene un significado especial dependiendo del siguiente carácter.

En la documentación de Python, en el bottem de la segunda tabla en esa sección, dice:

'%'        No argument is converted, results in a '%' character in the result.

Por lo tanto usted debe utilizar:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(tenga en cuenta el cambio expicit a tupla como argumento a %)

Sin saber lo anterior, habría hecho:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

Con el conocimiento que, obviamente, ya había.

 4
Author: Anthon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-28 18:43:45

Si la plantilla de formato se leyó desde un archivo, y no puede asegurarse de que el contenido duplique el signo de porcentaje, entonces probablemente tenga que detectar el carácter de porcentaje y decidir programáticamente si es el inicio de un marcador de posición o no. Entonces el analizador también debe reconocer secuencias como %d (y otras letras que se pueden usar), pero también %(xxx)s, etc.

Se puede observar un problema similar con los nuevos formatos the el texto puede contener llaves.

 3
Author: pepr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-22 07:27:15

He probado diferentes métodos para imprimir un título de subtrama, mira cómo funcionan. Es diferente cuando uso látex.

Funciona con '%%' y 'string'+'%' en un caso típico.

Si usa Latex, funcionó usando 'string' + '\% '

Así que en un caso típico:

import matplotlib.pyplot as plt
fig,ax = plt.subplots(4,1)
float_number = 4.17
ax[0].set_title('Total: (%1.2f' %float_number + '\%)')
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '%)')

Ejemplos de título con %

Si usamos látex:

import matplotlib.pyplot as plt
import matplotlib
font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 12}
matplotlib.rc('font', **font)
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.unicode'] = True
fig,ax = plt.subplots(4,1)
float_number = 4.17
#ax[0].set_title('Total: (%1.2f\%)' %float_number) This makes python crash
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '\%)')

Obtenemos esto: Ejemplo de título con % y latex

 -3
Author: user245554,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 22:29:26