7

I have a Python string which I want to \include in a latex file. However, my string has an underscore character (_), which needs to be converted into \_ (this is latex representation for _) before included.

If I do:

self.name = self.laser_comboBox.currentText() #Get name from a qt widget
latex_name = self.name.replace("_", r"\_") #Replacing _ for \_
print self.name
print latex_name

I'll get:

XXXXXX-YY\_SN2017060009
XXXXXX-YY\_SN2017060009

As, it can be seen, both variables got replaced. This means that the replace method happened inplace. However if I do:

self.name = self.laser_comboBox.currentText() #Get name from a qt widget
latex_name = str(self.name).replace("_", r"\_") #Converting to str and then replacing _ for \_
print self.name
print latex_name

I'll get:

XXXXXX-YY_SN2017060009
XXXXXX-YY\_SN2017060009

This is something that puzzled me..I'd like to know why this is happening...

Eduardo
  • 631
  • 1
  • 12
  • 25

2 Answers2

9

I've run some tests here and I think I've found the answer.

My var self.name has a <class 'PyQt4.QtCore.QString'> type, since I'm getting it from a QtWidget. Someone, please, correct me if I'm wrong but from the tests I run and from the docs (http://doc.qt.io/qt-5/qstring.html#replace) it seems that the replace method in <class 'PyQt4.QtCore.QString'> happens inplace. Whereas for the Python str, it does not since python strings are immutable.

So, in short:

  • Python str: inplace=False (Python strings are immutable)
  • PyQt4.QtCore.QString: inplace=True

Anyway, hope this can be helpful

Eduardo
  • 631
  • 1
  • 12
  • 25
0

When you do self.name you are actually replacing in place on the objects name string.

However when you do str(self.name) you are replacing on the new object created by str which is not self.name. Hence self.name remains unchanged.

coderadi
  • 35
  • 7