- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
› Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › CS105: Introduction to Python by Saylor Academy › Unit 8: Regular Expressions › Using Regular Expressions with mixed data types in Python: Safely handling non-string inputs
Source: Created with the help of ChatGPT
import re
personlist = ["axx ffbd", 56556, "acccb"]
pattern = "ax"
for x in personlist:
if re.match(pattern, x):
print(x)
Output:
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
ChatGPT:
In your code, you’re trying to match a regular expression pattern "ax" against each item in personlist. However, personlist contains both strings and non-string elements (like the integer 56556), and the re.match() function expects a string as its second argument. If it encounters an integer, it will raise a TypeError.
To avoid this, you should first check if the item is a string before attempting to use re.match() on it. Here’s how you can modify your code:
import re
personlist = ["axx ffbd", 56556, "acccb"]
pattern = "ax"
for x in personlist:
if isinstance(x, str): # Check if the element is a string
if re.match(pattern, x):
print(x)
isinstance(x, str): This checks if x is a string. Only if it is a string will the re.match() function be called."ax" will match strings starting with "ax", so "axx ffbd" will be printed because it matches the pattern.axx ffbd
The integer 56556 is safely skipped, and no errors occur.
