Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Str replace method happening inplace

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...

like image 421
Eduardo Avatar asked Jun 28 '17 12:06

Eduardo


1 Answers

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

like image 154
Eduardo Avatar answered Sep 28 '22 07:09

Eduardo