1

i have string like this:

string = "The stock item "28031 (111111: Test product)" was added successfully."

I need store from string the first 5 numbers ( for example "28031" ) and save them to another string.

It's because i am selenium tester and every time i am create new stock item he has different first 5 numbers.

Thank you for your help

Filip

4 Answers 4

3
m = re.search("\d+", string)
print m.group(0)

prints 28031

It just selects the first group of digits, regardless of the length (2803 would be selected, too)

Sign up to request clarification or add additional context in comments.

Comments

1

Firstly I am assuming all these strings have exactly the same format. If so the simplest way to get your stock item number is:

stocknumber = string.split()[3][1:]

Comments

1

After sehe answer I leave mine edited just to show how to match 5 digits

import re
re.search('\d{5}', string).group(0)

Comments

0

EDIT : neurino solution is the smartest!! use it

EDIT : sehe solution is smart and perfect you can add this line to get only the first 5 numbers:

print m.group(0)[0:5]

using [0:5] means to take string elements from 0 to 5 (first 5 elements)


use the str.isdigit built-in function

string = "The stock item 28031 "
Digitstring=''
for i in string:
    if i.isdigit():
        Digitstring+=i

print Digitstring

Output:

28031

you can count to first x numbers you need and then stop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.