Creating Strings and String Methods
Strings in Python are sequences of characters enclosed in single quotes, double quotes, or triple quotes. They are immutable, meaning once created, the characters inside a string cannot be changed individually.
Python provides a rich set of built-in string methods that return new strings rather than modifying the original.
Example
# Creating strings
single = 'Hello'
double = "World"
multi_line = """This is a
multi-line string."""
# Common string methods
text = " Hello, Python World! "
print(text.upper()) # " HELLO, PYTHON WORLD! "
print(text.lower()) # " hello, python world! "
print(text.strip()) # "Hello, Python World!"
print(text.replace("Python", "Coding")) # " Hello, Coding World! "
print(text.find("Python")) # 9 (index where 'Python' starts)
print(text.count("l")) # 2
# Split and join
words = "apple,banana,cherry"
fruit_list = words.split(",")
print(fruit_list) # ['apple', 'banana', 'cherry']
joined = " - ".join(fruit_list)
print(joined) # "apple - banana - cherry" - .upper() / .lower() — Convert to uppercase or lowercase
- .strip() / .lstrip() / .rstrip() — Remove whitespace from ends
- .replace(old, new) — Replace occurrences of a substring
- .find(sub) — Return the index of first occurrence, or -1 if not found
- .split(sep) — Split a string into a list by separator
- .join(list) — Join a list of strings with a separator
- .startswith() / .endswith() — Check if string starts or ends with a value
Try String Methods
JavaScript
text = " Hello, Python World! "
print(text.upper())
print(text.lower())
print(text.strip())
print(text.replace("Python", "Coding"))
words = "apple,banana,cherry"
fruit_list = words.split(",")
print(fruit_list)
print(" - ".join(fruit_list)) Notes
- String methods return new strings — they never modify the original string, because strings are immutable in Python.
F-Strings and String Slicing
F-strings (formatted string literals) were introduced in Python 3.6 and are the most readable way to embed expressions inside strings. Simply prefix the string with 'f' and put expressions in curly braces.
String slicing lets you extract portions of a string using the syntax string[start:stop:step]. The start index is inclusive, the stop index is exclusive.
Example
# F-strings
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
print(f"In 5 years I'll be {age + 5}.")
print(f"Pi is approximately {3.14159:.2f}") # Format to 2 decimals
# String slicing
text = "Hello, World!"
print(text[0]) # 'H' — first character
print(text[-1]) # '!' — last character
print(text[0:5]) # 'Hello' — index 0 to 4
print(text[7:]) # 'World!' — index 7 to end
print(text[:5]) # 'Hello' — start to index 4
print(text[::2]) # 'Hlo ol!' — every 2nd character
print(text[::-1]) # '!dlroW ,olleH' — reversed string - f"text {expression}" — embed variables and expressions directly
- f"{value:.2f}" — format numbers with decimal precision
- string[start:stop] — slice from start to stop-1
- string[::step] — slice with a step value
- string[::-1] — reverse a string
Try F-Strings and Slicing
JavaScript
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
print(f"In 5 years I'll be {age + 5}.")
text = "Hello, World!"
print(text[0:5])
print(text[7:])
print(text[::-1]) Notes
- F-strings are not only more readable than older formatting methods like .format() and %, they are also faster because they are evaluated at runtime.
