Member-only story
Python Coding challenge — Day 243 | What is the output of the following Python Code?
1 min readSep 8, 2024
In the code:
s = 'clcoding.com'
index = s.find('com')
print(index)
Explanation:
s = 'clcoding.com'
:
- This defines a string variable
s
with the value'clcoding.com'
.
index = s.find('com')
:
- The
find()
method searches for the substring'com'
in the strings
. - It returns the index of the first character of the first occurrence of the substring.
- If the substring is not found,
find()
returns-1
.
In this case, 'com'
is present in 'clcoding.com'
, and it starts at index 9.
print(index)
:
- This prints the value of
index
, which is 9.
String Breakdown:
The string 'clcoding.com'
has characters at the following positions:
Index: 0 1 2 3 4 5 6 7 8 9 10 11
Chars: c l c o d i n g . c o m
Here, the substring 'com'
starts at index 9.
Output:
9
The find()
method is useful for locating substrings within a string. In this case, it returns the index where 'com'
begins.