A string is a sequence of characters used to represent text. In Python, strings can include letters, digits, symbols, or spaces and are immutable — meaning once created, they cannot be changed. Python strings are enclosed in single quotes ('...') or double quotes ("...").
Example:
Key Features of Python Strings
-
Ordered Sequence: Characters have a defined sequence and can be accessed by index.
-
Immutable: Once created, the content cannot be changed without creating a new string.
-
Supports Indexing: You can access characters using positive and negative indices.
-
Supports Slicing: You can extract parts of a string using slicing syntax.
-
Flexible Text Handling: Strings can contain any textual data and support many built-in methods.
These features make strings a versatile and fundamental data type in Python.
String Indexing
Python assigns each character in a string a numerical index starting from 0 for the first character, and also supports negative indexing where -1 refers to the last character.
Example:
What Is String Slicing?
String slicing lets you extract a substring (a part of the string) by specifying a range of indices. The original string is not modified; slicing returns a new string.
Syntax
-
start – index where slice begins (inclusive).
-
end – index where slice stops (exclusive).
-
step – optional, determines interval between characters.
If start is omitted, slicing begins from the start of the string. If end is omitted, slicing goes until the end. If step is omitted, it defaults to 1.
Examples of String Slicing
1. Basic Slice
Extract a substring by specifying start and end.
2. Slice from Start
Omitting the start index begins slicing at the first character.
3. Slice to End
Omitting the end index slices until the end of the string.
4. Full Slice
Omitting both start and end returns a copy of the whole string.
5. Negative Index Slicing
A negative index starts counting from the end.
6. Using Step in Slicing
A step value lets you skip characters.
7. Reverse a String
Using a step of -1 reverses the string.
How Slicing Works Under the Hood
Strings in Python are sequences; slicing creates a new string containing the selected characters. The original string remains unchanged.