Home > Net >  How to check for string and get the string before after checking
How to check for string and get the string before after checking

Time:11-02

If I have a string "3 apples" and do a check like:

fruit = "3 apples"

if fruit.find('apples') > -1:

How can i get the number 3 before apple if the statement is true?

CodePudding user response:

Using str.split:

fruit = "3 apples"

num, word = fruit.split()
if word == 'apples':
    print(num)

Using re

import re

fruit = "3 apples"
match = re.match(r"(\d ) apples$", fruit)
if match:
    print(match.group(1))

CodePudding user response:

you can user index :

fruit = "3 apples"

if fruit.find('apples') > -1:
    print(fruit[0])

CodePudding user response:

fruit = "3 apples"
result = fruit.find('apple')
print(fruit[:result])
  • Related