0

How do I find the index of the numbers 0-9 in a string?

MyString = "Are all the black cats really black 045. I don't think so 098."
MyString.find([0-9])

TypeError: must be str, not list

How do I get around this and replicate what essentially is a PATINDEX in SQL server?. The following answer gives me a perspective of searching using regex but I am still unable to insert lists.

Vinay billa
  • 309
  • 2
  • 4
  • 17

1 Answers1

1

You can use a list comprehension to find the numbers:

>>> [MyString.find(str(i)) for i in range(10)]
[36, -1, -1, -1, 37, 38, -1, -1, 60, 59]

If you want the smallest number, you can use min:

>>> min([j for j in [MyString.find(str(i)) for i in range(10)] if j != -1])
36

Or you can use re.search for use with a regex pattern:

>>> import re
>>> re.search("[0-9]", MyString).start()
36

Remember to wrap the regex pattern in double quotes, otherwise it would be interpreted as a list of 0-9 (zero minus nine), which is -9.

mck
  • 40,932
  • 13
  • 35
  • 50
  • Thanks for this. However, I believe the actual position must be 37. I believe this is due to Python starting from 0. – Vinay billa Jan 20 '21 at 12:24
  • Yes, if you want to be consistent with SQL behaviour you need to add 1. @Vinaybilla – mck Jan 20 '21 at 12:25
  • Also, how do I go about if I need to start searching after position 10 similar to how we do for CHARINDEX in SQL? – Vinay billa Jan 20 '21 at 12:31
  • 1
    `min([j for j in [MyString.find(str(i)) for i in range(10)] if j >= 9])` @Vinaybilla – mck Jan 20 '21 at 12:32