0

doubt in pyhton strings...

if a string has not a particular substring that it throws an error but i want to print something and not want to see that error in terminal. how can i do that ? like an eg : string = "defghij" print (string.index("abc")) this code will throw an error 'ValueError : substring not found' but i want to print 'not found ' thats it and exit the program. can anyone solve this problem for me ?

19th Jun 2020, 8:54 AM
NIK
NIK - avatar
5 odpowiedzi
+ 7
First of all you should avoid using class names like string as variable names. If you need to get the position of a substring in an other string, find() is a good option. It returns the index position if found, and -1 when not found. But it only detects the first occurrence of the substring. Using index() and put it in a try except block is not very pythonic. An other possible solution (if you don’t need to get the index position) is using the membership operator "in". So it can look like this: txt = "defghij" sub = 'abc' print('Found') if sub in txt else print('NOT found')
19th Jun 2020, 9:56 AM
Lothar
Lothar - avatar
+ 3
You can use: string.find() If element isn't found it returns -1 if string.find("abc") == -1: print("not found") else: print(string.find("abc")) Also you can use exeptions: try: print(string.index("abc")) exept ValueError: print("not found") More about exeptions you can read in Python course in SoloLearn
19th Jun 2020, 9:04 AM
Maksim
Maksim - avatar
0
ohk thanks as i thought it is related to error handling i m not so much in that part now but thanks i will try this and i will be in that section soon so i can understand this code in that time.
19th Jun 2020, 9:05 AM
NIK
NIK - avatar
0
thanks both of u
19th Jun 2020, 9:06 AM
NIK
NIK - avatar