What will be the output of the following code:
string = "Python"
print(string[1:4])
print(string[1:4])
A. yth
B. ytho
C. thon
D. None of the above
Answer: Option A
Solution (By Examveda Team)
Understanding String Slicing in PythonIn Python, strings are sequences of characters. We can access parts of a string using slicing.
String slicing uses square brackets `[]` and a colon `:` to specify a range of characters. The format is `string[start:end]`.
The `start` index indicates where to begin (inclusive), and the `end` index indicates where to stop (exclusive).
Let's break down the code:
string = "Python"
This line assigns the string "Python" to the variable
string
.print(string[1:4])
This line uses slicing to extract a portion of the string. Let's analyze the indices:
-
1
(start index): This means we start at the second character (remember, Python uses zero-based indexing, so the first character is at index 0).-
4
(end index): This means we stop just before the fourth character.Therefore,
string[1:4]
will extract characters from index 1 ( 'y' ) up to, but not including, index 4. The Result:
The characters extracted are "yth".
Therefore, the correct answer is Option A: yth
Join The Discussion
Comments (1)
Related Questions on Strings in Python
Which of the following is the correct way to create a string in Python?
A. "Hello, World!"
B. 'Hello, World!'
C. "Hello, World!'
D. 'Hello, World!"
What does the len() function do when applied to a string?
A. Returns the length of the string
B. Converts the string to lowercase
C. Converts the string to uppercase
D. Removes leading whitespace
Which character is used to access individual elements of a string by index in Python?
A. . (period)
B. , (comma)
C. : (colon)
D. [ and ] (square brackets)
Hi, the answer is not C. The answer is A