1

I am parsing a bunch of HTML and am encountering a lot of "\n" and "\t" inside the code. So I am using

"something\t\n here".replace("\t","").replace("\n","")

This works, but I'm using it often. Is there a way to define a string function, along the lines of replace itself (or find, index, format, etc.) that will pretty my code a little, something like

"something\t\n here".noTabsOrNewlines()

I tried

class str:
    def noTabNewline(self):
        self.replace("\t","").replace("\n","")

but that was no good. Thanks for any help.

6
  • you are on track with creating a class and using a method to perform your funciton.. make sure you read up on classes and objects Commented May 26, 2016 at 3:34
  • 1
    github.com/clarete/forbiddenfruit <-- here be dragons Commented May 26, 2016 at 3:35
  • What about using noTabsOrNewlines("something\t\n here") instead? Commented May 26, 2016 at 3:43
  • @RyanAmos Thanks. That'll do perfectly. Of course now I'm still curious about how to define a method that will appear after "something".<<here>> Commented May 26, 2016 at 3:47
  • @BrandonMacer: You can't add methods to builtin types. Commented May 26, 2016 at 3:53

2 Answers 2

1

While you could do something along these lines (https://stackoverflow.com/a/4698550/1867876), the more Pythonic thing to do would be:

myString = "something\t\n here" ' '.join(myString.split())

You can see this thread for more information: Strip spaces/tabs/newlines - python

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

2 Comments

I'll take this because it's pretty and that's what I wanted, though my curiosity remains for adding methods to "something" (or [somethings] or (somethings), for that matter)
You can see this previous post at stackoverflow.com/a/4698550/1867876. I updated my answer to include this above.
1

you can try encoding='utf-8'. otherwise in my opinion there is no other way otherthan replacing it . python also replaces it spaces with '/xa0' so in anyway you have to replace it. our you can read it line by line via (readline()) instead of just read() it .

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.