Python String Type
What Is a String?
A string (str) is an immutable sequence of Unicode characters, used to store and represent text in Python. Strings can contain letters, numbers, symbols, and even whitespace.
Creating Strings
You can create strings using single quotes, double quotes, or triple quotes for multi-line strings:
s1 = 'Hello'
s2 = "World"
s3 = '''This is
a multi-line string.'''
s4 = """Another
multi-line string."""
from_object = str(123) # '123'
Accessing and Slicing Strings
You can access characters by index and slice strings:
text = "Python"
print(text[0]) # 'P'
print(text[-1]) # 'n'
print(text[1:4]) # 'yth'
Common String Operations
Strings support many operations:
s = "abc"
print(len(s)) # 3
print(s + "def") # 'abcdef' (concatenation)
print(s * 2) # 'abcabc' (repetition)
print("b" in s) # True (membership)
String Methods
Strings have many built-in methods for manipulating text:
s = " Python "
print(s.strip()) # 'Python' (remove whitespace)
print(s.lower()) # ' python '
print(s.upper()) # ' PYTHON '
print(s.replace("P", "J")) # ' Jython '
print(s.startswith(" Py")) # True
print(s.endswith("on ")) # True
print(s.count("o")) # 1
print(s.find("th")) # 4
print(s.split()) # ['Python']
print("-".join(["a", "b"])) # 'a-b'
String Formatting
Python supports several ways to format strings:
name = "Alice"
age = 30
print(f"{name} is {age} years old.") # f-string
print("{} is {} years old.".format(name, age))
print("%s is %d years old." % (name, age))
Iterating Over Strings
You can loop through strings using a for
loop:
for char in "hi!":
print(char)
Immutability of Strings
Strings cannot be changed after creation. Any operation that modifies a string returns a new string:
s = "hello"
# s[0] = "H" # Error! Strings are immutable
s2 = s.replace("h", "H") # 'Hello'
Summary
- Strings are immutable sequences of Unicode characters for storing text.
- Support indexing, slicing, and many built-in methods.
- Use single, double, or triple quotes to create strings.
- Strings are widely used for text processing in Python.