Python Strings
Python Strings
Master Python strings with slicing, methods, f-strings, and string formatting techniques.
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello"
You can display a string literal with the print() function.
Multiline Strings
You can assign a multiline string to a variable by using three quotes.
String Methods
Python has a set of built-in methods that you can use on strings. Some important methods:
| Method | Description |
|---|---|
upper() | Returns uppercase string |
lower() | Returns lowercase string |
strip() | Removes whitespace |
replace() | Replaces a substring |
split() | Splits into a list |
find() | Finds substring index |
count() | Counts occurrences |
startswith() | Checks prefix |
endswith() | Checks suffix |
String Formatting
f-strings (formatted string literals) are the modern way to format strings in Python (Python 3.6+).
Example
python
# String basics
greeting = "Hello, World!"
print(len(greeting)) # 13
print(greeting[0]) # H
print(greeting[-1]) # !
print(greeting[0:5]) # Hello
print(greeting[7:]) # World!
# String methods
text = " Python is Amazing! "
print(text.strip()) # "Python is Amazing!"
print(text.lower()) # " python is amazing! "
print(text.upper()) # " PYTHON IS AMAZING! "
print(text.replace("Amazing", "Powerful"))
# String splitting
words = "apple,banana,cherry".split(",")
print(words) # ['apple', 'banana', 'cherry']
# f-strings (Python 3.6+)
name = "Alice"
age = 28
lang = "Python"
print(f"Hi, I'm {name}, age {age}, learning {lang}!")
print(f"2 + 2 = {2 + 2}")
print(f"Pi is approximately {3.14159:.2f}")
# String check methods
email = "user@example.com"
print(email.endswith(".com")) # True
print("123".isnumeric()) # TrueTry it yourself — PYTHON