How to Print Specific Parts of a String in Python?

Estimated read time 1 min read

In Python, you can print specific parts of a string using slicing. Slicing allows you to extract a substring from a string based on its indices. Here’s an example:

# Define a string
string = "Hello, World!"

# Print the first five characters of the string
print(string[0:5])  # Output: "Hello"

# Print the characters from index 7 to the end of the string
print(string[7:])  # Output: "World!"

In the first print statement, we use slicing to extract the characters from index 0 to index 4 (inclusive), which gives us the first five characters of the string.

In the second print statement, we use slicing to extract the characters from index 7 to the end of the string. Since we don’t specify an end index, Python assumes that we want to slice until the end of the string.

You can also use negative indices in slicing to count from the end of the string. For example:

# Print the last five characters of the string
print(string[-5:])  # Output: "orld!"

Here, we use a negative index to specify that we want to start slicing from the fifth character from the end of the string, and slice until the end of the string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply