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

Time:04-08

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:

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?

CodePudding user response:

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

CodePudding user response:

signpos =  list.find(" ") or list.find("-")

If the string does not have a plus sign, the first find() call will return -1 which is a non-false value, so the second find() will not be executed, and signpos will be assigned -1.

This probably isn't what you wanted.

  • Related