How to Check an Array for Strings in Python
Programmers generally refer to Python as a scripting language. One of the reasons for this is because it has many built-in functions to perform repetitive or interesting tasks, and requires little in the way of coding to accomplish. Therefore, many Python programs are less verbose and easier to read than programs in other languages. As an example, checking an array, or list of items, for string data types is as quick as calling the "isinstance()" built-in function.
Instructions
-
-
1
Declare a list of items and populate it with data. Some of the data items should be strings, and some other types. This example uses integers:
>>>l = {"hello", 2, 3, "Hi", "4", 85, "5", 89, 9)
-
2
Create a "for" loop that loops over the list and checks each item, one at a time:
>>>for item in l:
. . . -
-
3
Create an "if" statement in the "for" loop that checks each item's data type. If the type is a string, or "str," then the "if" statement executes:
>>>for item in l:
. . . if isinstance(item, str): -
4
Print the index of each item in the list that represents a string:
>>>for item in l:
. . . if isinstance(item, str):
. . . print l.index(item)
-
1