Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #54366 > unrolled thread
| Started by | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| First post | 2013-09-18 11:50 +0200 |
| Last post | 2013-09-18 11:50 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Remove \n, " " from tuple. Vlastimil Brom <vlastimil.brom@gmail.com> - 2013-09-18 11:50 +0200
| From | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| Date | 2013-09-18 11:50 +0200 |
| Subject | Re: Remove \n, " " from tuple. |
| Message-ID | <mailman.112.1379497852.18130.python-list@python.org> |
[Multipart message — attachments visible in raw view] — view raw
2013/9/18 Venkat Addala <venkat.boffin@gmail.com>
> Hi all,
>
> I have a tuple in this format, which is retrived using MySQLdb, now i want
> to remove \n and extra spaces in this.
>
> 13L, 'ssDsC', 'CEs5s1, DsC', 'srylscetsmight\nghtscetylsse', '3',
> '3q25.1', 151531861L, 151546276L, '+', '1 kjafhkfhlad\fdfdsdf ghtscetylsse
> \ncontends the sctivity of dsfdk srylsmine N-scetyltrsnsfersse thst scts ss
> s cstslyst inbiotrsnsformstion fghjfg for srylsmine snd bvhghbh smine
> csrcinogens. Bgskjdg in ssDsC dfkdkdf in bresst snd prostrste csncer.', '',
> 'Msdhurs \nsgdfgssssvslingegowds', dstetime.dste(2013, 6, 14), None
>
>
>
> --
> Regards
> Venkat Addala <http://in.linkedin.com/in/venkataddala/>
> Computational Biologist
> O__ ----
> _/ /`_ ---
> (*) \(*) --
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
> Hi,
you can create a new tuple with the converted elements from the original one
using a list comprehension and the regular expression replacement, it could
be e.g.
>>> import re
>>> tuple([re.sub(r"\s+", " ", element) if isinstance(element, str) else
element for element in ("qw e", 1, 2, None, "U\nN IC", 'Q\tW E')])
('qw e', 1, 2, None, 'U N IC', 'Q W E')
>>>
re.sub(...) replaces one or more whitespace characters (space, newline, tab
...) with a single space - the pattern can be tweaked as needed (e.g. the
pattern r" *\n *| +" would only handle spaces and newlines explicitely).
This replacement is only applied on string elements of the tuple, others
are left unchanged
if isinstance(element, str) is meant for python 3, for python 2 if
isinstance(element, basestring) would be more appropriate
the elements are collected in a list using this list comprehension
and this intermediate list is finaly converted to a tuple if this immutable
container is needed.
hth,
vbr
Back to top | Article view | comp.lang.python
csiph-web