5

I currently have the following list:

data = [('b','..','o','b'),('t','s','..','t')]

I am trying to figure out a way to replace all instances of the '..' string to another string. In my instance, the string of ' '.

I have attempted to use the built-in function using the following method, but had no luck.

newData = list(map(lambda i: str.replace(i, ".."," "), data))

Could someone point me in the right direction? My desired output would be the following:

newData = [('b',' ','o','b'),('t','s',' ','t')]
taytortot
  • 99
  • 1
  • 2
  • 5

2 Answers2

3

You can use a list comprehension with a conditional expression:

>>> data = [('b','..','o','b'),('t','s','..','t')]
>>> newData = [tuple(s if s != ".." else " " for s in tup) for tup in data]
>>> newData
[('b', ' ', 'o', 'b'), ('t', 's', ' ', 't')]
>>>
Community
  • 1
  • 1
  • Thanks! This worked flawlessly. I understand where the variable of s comes into play, but could you explain to me the purpose of the "tup" variable? – taytortot Apr 14 '14 at 21:32
  • 1
    @taytortot - Certainly. The `for tup in data` clause will iterate over each item (tuple) inside the list `data`. It will take each one, store it in the variable `tup`, and then send it to the `tuple(s if s != ".." else " " for s in tup)` part. I named the variable `tup` to represent "tuple". –  Apr 14 '14 at 21:36
  • @iCodez It might be easier to show what the `tup` variable is for if you show the equivalent nested `for` loops. – SethMMorton Apr 14 '14 at 22:04
3

Map operates on each of the elements of the list given. So in this case, your lambda expression is being called on a tuple, not the elements of the tuple as you intended.

wrapping your code in a list comprehension would do it:

newData = [tuple(map(lambda i: str.replace(i, ".."," "), tup)) for tup in data]
joc
  • 1,058
  • 7
  • 8