简体   繁体   中英

Replacing “<” with “*” with a Python regex

I need to go through strings in a list "listb", replacing the character "<" with "*".

I tried like this:

import re
for i in listb:
    i = re.sub('\<','\*', 0)

But I keep getting TypeError: expected string or buffer.

Not sure what am I doing wrong and examples on the net were not much help.

See the docs

As per Seth's comment, the best way to do this using regular expressions is going to be:

listb = [re.sub(r'<',r'*', i) for i in listb]

As @Paco, said, you should be using str.replace() instead. But if you still want to use re:

You're putting 0 where the string is supposed to go! The TypeError is from the that third parameter. It's an int, needs to be a string.

Side note: always use raw strings, denoted by r'' , in your regexes, so you don't have to escape.

>>> listb = ['abc', '<asd*', '<<>>**']
>>> for i in listb:
...     i = re.sub(r'<',r'*', i)
...     print i
... 
abc
*asd*
**>>**
>>> listb
['abc', '<asd*', '<<>>**']

if you want a new list with all those replaced, do:

>>> listx = []
>>> for i in listb:
...     listx.append(re.sub(r'<',r'*', i))
... 
>>> listx
['abc', '*asd*', '**>>**']
>>> listb
['abc', '<asd*', '<<>>**']
>>> listb = listx

If you really don't want to create a new list, you can iterate through the indices.

Note that you're not changing i in the list. I would create a new list here. Each i here is its own variable, which doesn't point to listb.

>>> my_string = 'fowiejf<woiefjweF<woeiufjweofj'
>>> my_string.replace('<', '*')
'fowiejf*woiefjweF*woeiufjweofj'

Why are you using the re module for such a simple thing? you can use the .replace method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM