Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to find specific character in string list python?

I have a list which contains string values taht represents calculations. From them I want to get a specific character, let’s say plus and minus signs.

I tried using var1.find('a') != -1 or var.find('z') != -1 as suggested here Python: Using AND and OR with .FIND() method, but I’m still getting -1 when I try ‘-‘.

Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lists = ["22 + 13", "4500 - 2"]
for list in lists :
  if (list.find('+') or (list.find('-')) != -1) :
    signpos =  list.find("+") or list.find("-")
    print(signpos)
  else:
    print('Error')

I get 3 aand -1 as results, where the desire output should be 3 and 5.

What I’m not seeing?

>Solution :

As others suggested, don’t use list as a variable name. It is a type.

lists = ["22 + 13", "4500 - 2"]
for string in lists:
  signPos = None

  if "+" in string:
    signPos = string.find("+")
  elif "-" in string:
    signPos = string.find("-")
  else:
    print('Error')
    
  print(signPos)

# Output
# 3
# 5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading