Python String Slicing: Get First Characters
When accessing specific characters in a string using indexes, the counting starts from 0. To retrieve the first two characters, we can utilize slicing. Slicing allows us to extract a portion of a string based on specified start and end indexes.
In Python, we can use the following syntax to get slices of a string:
string[start:end]
- Starting index: the initial position from which the slicing should begin, by default it is 0 (which is the beginning of the string).
- End: The ending index, indicating the end position of the slice (excluding the character at that position). If this parameter is not provided, it defaults to the length of the string.
Therefore, to obtain the first two characters of a string, we can set the start index to 0 and the end index to 2 (excluding the character at index 2), as shown below:
string = "Hello, World!"
first_two_chars = string[0:2]
This will return a new string containing the first two characters from the original string (“He”). Finally, we can use the print() function to print the result.
print(first_two_chars)
After executing the above code, it will output: “He” as the result.