5

Is there an easy way (hopefully a one liner) to replace '' with something like '-'?
Many thanks.

tup = (1,2,'ABC','','','','text')
3
  • 2
    stackoverflow.com/questions/1175540/… Commented Mar 4, 2011 at 22:54
  • 3
    I hope you are aware that tuples are immutable. You can do it, but that will create a new tuple (so references might break). Commented Mar 4, 2011 at 22:54
  • 2
    Why do people specifically want one-liners? Commented Mar 5, 2011 at 1:45

1 Answer 1

16

How about the following?

 tuple('-' if x == '' else x for x in tup)

As Felix Kling comments, tuples are immutable, so the best you can do is to return a new one.

Sign up to request clarification or add additional context in comments.

4 Comments

As a very minor point, I'd probably reverse it and write it as tuple(x if x != '' else '-' for x in tup), since the usual, expected case is non-empty.
@Adam Rosenfield: Or more succinctly: tuple(x if x else '-' for x in tup)
@Adeel: That won't work if OP wants to preserve other values interpreted as false, such as False, 0, [], etc.
@Adam Rosenfield: You are absolutely correct. Despite the example provided by the OP, I erroneously assumed that the tuple is homogeneous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.