-3
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x) // True

txt = "The rain in Spain stays mainly in the plain "
x = " " in txt
print(x) // True

txt = "The rain in Spain stays mainly in the plain "
x = " " in txt.strip()

print(x) // True ,

Even after removing whitespaces it is giving truthy.

Code Pope
  • 5,075
  • 8
  • 26
  • 68
user3215183
  • 19
  • 1
  • 3
  • this is realy true synce " " is a string and "" is a string to – Jasar Orion May 14 '20 at 12:33
  • 2
    `strip` doesn't remove all whitespace. It only removes leading and trailing whitespace. The obvious check would have been to `print(txt)` to see what you were doing. Try it. – Tom Karzes May 14 '20 at 12:34
  • Well, operator `in` checks if string contains given argument and in your examples string actually does contain every arguments you check it against. – Michail Highkhan May 14 '20 at 12:35

4 Answers4

4

strip() only removes leading and trailing whitespace, not all spaces within the string.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
1

txt.replace(" ", "") this will remove all the spaces.

If you also want to remove other whitespaces,

txt = "".join(txt.split())
Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
0

strip() removes both leading and trailing characters. Means the text would look like this

"The rain in Spain stays mainly in the plain"

but there are still whitespace between words

0
txt = "The rain in Spain stays mainly in the plain "
txt.strip()

Output:

'The rain in Spain stays mainly in the plain'

stript() just removes the spaces at the beginning and the end and not the spaces in betwen the string. Therefor the following statement is true:

x = " " in txt.strip()
print(x)

Output:

True

There are many ways to remove all spaces in a string:

1. split()

''.join(txt.split())

2. replace()

txt.replace(" ", "")

3. Regular expression:

import re
stringWithoutSpaces = re.sub(r"\s+", "", txt, flags=re.UNICODE)

The output of all of them is:

'TheraininSpainstaysmainlyintheplain'
Code Pope
  • 5,075
  • 8
  • 26
  • 68