Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the  below string

 "Halo Device ANumber : 6232123123 Customer ID : 16926"

I want to search with the keyword: "62" from the string.

Then if I want to show it's whole substring "6232123123" . I am using the below code:

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')

ind = string.find('62')

word = string.split()[ind]

print('62 found in index: ', ind)

print('substring : ', word)

And getting this output:

62 found in index:  22

substring : Device

1 Answer

0 votes
by (36.8k points)

If you are looking for the particular "full string", where it ends when there is simply the space, you can just use .find() again:

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')

target = '62'

ind = string.find(target)

ind_end = string.find(' ', ind + len(target))

word = string[ind:ind_end]

If you wanted something more robust, we can use regex:

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')

word = re.findall('(62\d+)', string).groups()[0]

This will take a first match from your string which starts from "62" and captures all the remaining numerical digits.

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...