Hi, I noticed an outlier and I wanted to get some thoughts on this particular topic.
In
Business Intelligence Data Analyst
Python Strings: Medical Insurance Project
I noticed something odd, i.e., the strip() is used to remove the specified character from the string. If no parameters are passed, whitespace from the beginning and end of the string is automatically removed.
I noticed that when I used
“item = item.strip()” it stripped both whitespace and carriage returns (i.e., \n)
What causes this variance or can we simply use string.strip() to remove unnecessary characters?
Thanks for your response in advance.
Strip removes whitespace for the ends of a string by default. The question to ask is what is whitespace? Is it just spaces or something else?
There’s a simple answer to that. In an interactive console you can do
>>> import string
>>> string.whitespace
' \t\n\r\x0b\x0c' # these are all the ascii characters considered whitespace
Source: string — Common string operations — Python 3.12.5 documentation
There is no variance to speak of, it is well-defined (meaning that given a string input, the output is determinate and unique).
Usually if you want more specific behavior you will have to use a few methods in conjunction to achieve it, or you always have the ability to use regex, although that’s more of a power-tool for this scenario.
3 Likes
It makes more sense, why it removed all return carriages and tabs from the text.
Thanks for your answer, Have a great day.