› 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
- This topic is empty.
-
AuthorPosts
-
August 23, 2024 at 5:32 am #3270
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 objectChatGPT:
In your code, you’re trying to match a regular expression pattern
"ax"against each item inpersonlist. However,personlistcontains both strings and non-string elements (like the integer56556), and there.match()function expects a string as its second argument. If it encounters an integer, it will raise aTypeError.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)Explanation:
isinstance(x, str): This checks ifxis a string. Only if it is a string will there.match()function be called.- The pattern
"ax"will match strings starting with"ax", so"axx ffbd"will be printed because it matches the pattern.
Output:
axx ffbdThe integer
56556is safely skipped, and no errors occur. -
AuthorPosts
- You must be logged in to reply to this topic.


