小能豆

Confused by the .find() function

java

I’m currently taking the Codecademy python course. I wanted to iterate through the strings in a list and add any of the strings that show a dollar amount to the sales list, so naturally I wrote:

if transactions_clean[i].find('$') == True:
      sales.append(transactions_clean[i])

But this returned an empty list. Just as a random attempt to make something work, I changed it to

if transactions_clean[i].find('$') == False:
      sales.append(transactions_clean[i])

and suddenly the list contained every dollar amount in the original (transactions_clean) list. If I’m reading this right, its saying if you don’t find the dollar sign in a string, add that string to the sales list… so why did it add every item that contained a dollar sign to the list? If anyone wants to look at the exact problem it is the Codecademy Learn Python 3 Course under strings -> Thread Shed challenge problem. Thanks!


阅读 67

收藏
2023-11-23

共1个答案

小能豆

The issue you’re facing is related to how the find method works. The find method returns the index of the first occurrence of the specified value in the string. If the value is not found, it returns -1.

In Python, when you use if transactions_clean[i].find('$') == True:, it checks if the result of find('$') is equal to True. However, find('$') will return an integer (the index of the dollar sign) or -1 if the dollar sign is not found. In Python, any non-zero integer is considered True in a boolean context. So, your condition will be true for any string where the dollar sign is found, which is not what you want.

To check if a substring is present in a string, you should use the in operator or the find method directly. Here’s an example using the in operator:

if '$' in transactions_clean[i]:
    sales.append(transactions_clean[i])

Alternatively, using the find method:

if transactions_clean[i].find('$') != -1:
    sales.append(transactions_clean[i])

Both of these conditions check if the dollar sign (‘$’) is present in the string, and if so, it appends the string to the sales list.

2023-11-23