String Operations in Python
- String operations are an essential part of Python programming. Strings are sequences of characters, and Python provides powerful tools to access, modify, and manipulate them easily.
String Operations in Python
Indexing
Indexing is used to access individual characters in a string.
Index positions start from 0 (left to right) and -1 (right to left).
Accessing Characters Using Index
This example shows how to access characters using positive and negative indexing.
text = "Python"
print(text[0]) # P
print(text[-1]) # n
Slicing
Slicing is used to extract a part of a string.
It uses the format: string[start:end].
String Slicing
This example extracts a portion of a string using slicing.
text = "Programming"
print(text[0:6]) # Progra
Step Slicing
Step slicing extracts characters by skipping values.
It uses the format: string[start:end:step].
Step Slicing
This example prints every second character from the string.
text = "Python"
print(text[0:6:2]) # Pto
Concatenation
Concatenation is used to join two or more strings.
The + operator is used for concatenation.
String Concatenation
This example combines two strings into one.
first = "Hello"
second = "Python"
print(first + " " + second)
Repetition
Repetition repeats a string multiple times.
The * operator is used for string repetition.
String Repetition
This example repeats a string three times.
text = "Hi "
print(text * 3)