classification
Title: Please add an equivalent to QString::simplified() to Python strings
Type: enhancement Stage: resolved
Components: Interpreter Core Versions: Python 3.3
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: l3u, r.david.murray, serhiy.storchaka
Priority: normal Keywords:

Created on 2014-08-03 13:18 by l3u, last changed 2014-08-05 18:35 by r.david.murray. This issue is now closed.

Messages (3)
msg224633 - (view) Author: Tobias Leupold (l3u) Date: 2014-08-03 13:18
It would be nice if a function equivalent to Qt's QString::simplified() would be added to Python's strings (cf. http://qt-project.org/doc/qt-4.8/qstring.html#simplified ).

I'm not sure if my approach is good or fast, but I added this function to my code like so: http://nasauber.de/blog/T/143/QString_simplified_in_Python
msg224638 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2014-08-03 13:39
This is too specialized function to be included in the stdlib ar added as a method to base class.

There are simpler and faster implementations of this function:

    def simplify(s):
        return ' '.join(s.strip().split())

or

    def simplify(s):
        return re.sub(r'\s+', ' ', s.strip())

Due to they simplicity there is no need to add them in Python.
msg224871 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2014-08-05 18:35
Actually, we more or less already do have this function in the stdlib, (I'd guess it is for pretty much the same reason that QT has it), except ours can also truncate sensibly to a given width:

  >>> import textwrap
  >>> textwrap.shorten('  lots\t of\nwhitespace\r\n ', 99999)
  'lots of whitespace'
  >>> textwrap.shorten('  lots\t of\nwhitespace\r\n ', 15)
  'lots of [...]'


That said, if you want *just* the white-space-stripping, the ' '.join(s.strip().split()) expression is just as useful and (for what it is worth) faster.
History
Date User Action Args
2014-08-05 18:35:20r.david.murraysetnosy: + r.david.murray
messages: + msg224871
2014-08-03 13:39:09serhiy.storchakasetstatus: open -> closed

nosy: + serhiy.storchaka
messages: + msg224638

resolution: rejected
stage: resolved
2014-08-03 13:18:36l3ucreate