How to Determine if a Character Is Whitespace in Python

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
Show More

Instructions

    • 1

      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'

    • 2

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

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

    • 3

      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

Related Searches:

References

Comments

Related Ads

Featured