1

End up writing lots of:

lines = [l.strip() for l in lines]

Is there a readable Pythonista way to do it like: lines.stripped() that returns lines stripped? (in C# you could add an 'extension method' to a list of strings).

2
  • 2
    I don't have an answer to your second question but your first can be shortened to: map(str.strip,lines). The list comp is also fine in my opinion, i'm not saying that is more pythonic. Commented May 7, 2012 at 9:40
  • 1
    Token SO response: have you considered (l.strip() for l in lines) instead? Commented May 7, 2012 at 10:05

2 Answers 2

5

No, you can't monkeypatch the list type. You can create a subclass of list with such a method, but this is probably a poor idea.

The Pythonic way to capture oft-repeated bits of code is to write a function:

def stripped(strings):
    return [s.strip() for s in strings]
Sign up to request clarification or add additional context in comments.

2 Comments

yes, i did your way, but it is still less readable than extension method (usually reading the code from the left to right, but here reading of internal part is required to be first, and after that a left part comes: stripped(text.split('\n'))
why is it bad idea to subclass list?
2

There is https://github.com/clarete/forbiddenfruit

Wether you consider it readable Pythonista is personal choice. But it does work.

I do wish Python had something like CSharp, Kotlin, Scala, Ruby "Extension Methods". Until then forbiddenfruit or the technique it uses (which can be simplified significantly) is the only way I know.

Comments

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.