How to Determine if a Character Is Whitespace in Python

Save

One of Python's strengths comes from its ability to handle collections of data such as lists or strings. When you handle strings in Python, many built-in functions ease simple tasks such as checking string length or stripping out white space. For example, using the "isspace" function allows you to check for white space characters in a string.

Things You'll Need

  • Python Interpreter
  • Create a string with white space characters, which includes blank spaces (" "), tab characters ("\t") and new line characters ("\n"):

    s = 'This is a string \t\n'

  • Create a "for" loop to iterate over each character in the string (Source 1):

    for i in range(len(s)):
    . . .

  • Use an "if" statement in the for loop to check for white space, and print the index of the string where white space occurs (Source 2):

    for i in range(len(s)):
    . . . if s[i].isspace():
    . . . print i
    4
    7
    9
    16
    17
    18

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!