Strings are one of the most widely used data types in Python. Whether you're working with user input, files, or APIs, strings will be a core part of your programming journey. In this guide, we’ll explore how to create strings, access specific characters, slice them into parts, and understand why strings in Python are immutable.
Example 1: Creating Strings
message = "Hello, Python"
print(message)
Strings in Python can be created using single or double quotes. Both work the same way.
Example 2: Multi-line Strings
paragraph = """This is a
multi-line string in
Python."""
print(paragraph)
Triple quotes allow you to create multi-line strings, useful for long messages or documentation.
Example 3: Indexing Strings
text = "Python"
print(text[0]) # First character
print(text[3]) # Fourth character
Strings in Python are indexed from 0. You can use square brackets to access individual characters.
Example 4: Negative Indexing
word = "Developer"
print(word[-1]) # Last character
print(word[-3]) # Third-last character
Negative indexing allows you to access characters from the end of the string.
Example 5: String Slicing
language = "Programming"
print(language[0:6]) # 'Progra'
print(language[3:9]) # 'grammi'
Slicing lets you extract a portion of a string. The syntax is string[start:end]
, and the end index is not included.
Example 6: Slicing with Step
code = "Python3.10"
print(code[0:10:2]) # Skips every second character
You can add a step value to the slice to skip characters or reverse strings.
Example 7: Reversing a String
name = "OpenAI"
reversed_name = name[::-1]
print(reversed_name)
Using slicing with a negative step reverses the string. A common technique for string reversal in Python.
Example 8: String Immutability
word = "Data"
# word[0] = "M" # This will raise an error
new_word = "M" + word[1:]
print(new_word)
Strings in Python are immutable, meaning you cannot change individual characters. You can, however, create new strings by combining slices.
Example 9: Length of a String
sentence = "Python is fun"
print(len(sentence))
The len()
function returns the number of characters in a string, including spaces.
Example 10: Checking Membership
quote = "Knowledge is power"
print("power" in quote)
print("wisdom" not in quote)
You can use in
and not in
to check if a substring exists within a string.
Summary
- Strings can be created using single, double, or triple quotes.
- Indexing starts from 0; negative indexing starts from the end.
- Slicing lets you extract specific parts of a string using the syntax
[start:end:step]
. - Strings are immutable — they cannot be changed after creation.
- You can reverse, check membership, and measure length using built-in functions and operators.
Understanding strings deeply will help you manipulate and analyze text effectively in Python, whether you're parsing data or building applications.