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 ?
4 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')
+ 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
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.
0
thanks both of u