Python in Python is best learned by connecting the rule to an automation script. Start with the smallest function or script, observe the output, and then add one realistic constraint so the concept becomes practical.
The key habit for this lesson is to watch input value and returned object as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.
A string is a sequence of characters enclosed in single, double, or triple quotes. Strings are immutable - once created, they cannot be changed in place.
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''triple single - spans
multiple lines'''
s4 = """triple double - also
multi-line"""
# Escape characters
tab = "Hello\tWorld" # tab
newline = "Line1\nLine2" # newline
quote = "She said \"hi\""
backslash = "C:\\Users\\Alice"
# Raw string - backslashes are literal
path = r"C:\Users\Alice\Documents"
regex = r"\d+\.\d+"
print(len("Python")) # 6
print(type("hello")) # <class 'str'>
s = "Python"
# P y t h o n
# 0 1 2 3 4 5 (positive index)
# -6-5-4-3-2-1 (negative index)
print(s[0]) # P
print(s[-1]) # n
print(s[2]) # t
# Slicing: s[start:stop:step]
print(s[1:4]) # yth
print(s[:3]) # Pyt
print(s[3:]) # hon
print(s[::2]) # Pto (every 2nd char)
print(s[::-1]) # nohtyP (reversed)
# Strings are immutable
# s[0] = "J" # TypeError!
# Create a new string instead:
new_s = "J" + s[1:]
print(new_s) # Jython
name = "Alice"
age = 25
pi = 3.14159
# f-strings (Python 3.6+) - recommended
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi = {pi:.2f}") # 2 decimal places
print(f"{age:05d}") # 00025 (zero-padded)
print(f"{'left':<10}|") # left-aligned
print(f"{'right':>10}|") # right-aligned
print(f"{'center':^10}|") # centered
print(f"{1_000_000:,}") # 1,000,000 (thousands separator)
# format() method
print("Hello, {}! Age: {}".format(name, age))
print("Hello, {name}!".format(name="Bob"))
# % formatting (old style)
print("Hello, %s! Age: %d" % (name, age))
print("Pi = %.2f" % pi)
# Multiline f-string
report = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Pi: {pi:.4f}"
)
print(report)
| Method | Description | Example |
|---|---|---|
| upper() | Uppercase | "hi".upper() -> "HI" |
| lower() | Lowercase | "HI".lower() -> "hi" |
| title() | Title case | "hello world".title() -> "Hello World" |
| strip() | Remove leading/trailing whitespace | " hi ".strip() -> "hi" |
| lstrip() / rstrip() | Strip left or right only | |
| replace(old, new) | Replace substring | "abc".replace("b","x") -> "axc" |
| split(sep) | Split into list | "a,b,c".split(",") -> ['a','b','c'] |
| join(iterable) | Join list into string | ",".join(["a","b"]) -> "a,b" |
| find(sub) | Index of first occurrence (-1 if not found) | "hello".find("l") -> 2 |
| index(sub) | Like find but raises ValueError | |
| count(sub) | Count occurrences | "hello".count("l") -> 2 |
| startswith(s) | Check prefix | "hello".startswith("he") -> True |
| endswith(s) | Check suffix | "hello".endswith("lo") -> True |
| isdigit() | All digits? | "123".isdigit() -> True |
| isalpha() | All letters? | "abc".isalpha() -> True |
| isalnum() | Letters or digits? | |
| zfill(n) | Zero-pad to width n | "42".zfill(5) -> "00042" |
| center(n) | Center in width n | "hi".center(10) |
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
print(" | ".join(fruits)) # apple | banana | cherry
sentence = "the quick brown fox"
print(sentence.title()) # The Quick Brown Fox
print(sentence.count("the")) # 1
print(sentence.find("quick")) # 4
print(sentence.startswith("the")) # True
# Method chaining
clean = " HELLO WORLD ".strip().lower().replace(" ", "_")
print(clean) # hello_world
# Concatenation
first = "Hello"
last = "World"
full = first + ", " + last + "!"
print(full) # Hello, World!
# Repetition
print("ha" * 3) # hahaha
print("-" * 30) # separator line
# Membership
print("ell" in "Hello") # True
print("xyz" not in "Hello") # True
# Iteration
for char in "Python":
print(char, end=" ") # P y t h o n
# Convert to list of chars
chars = list("Python")
print(chars) # ['P', 'y', 't', 'h', 'o', 'n']
# Multiline string as template
template = """
Dear {name},
Your order #{order_id} has been shipped.
Expected delivery: {date}
Thanks,
The Team
"""
print(template.format(name="Alice", order_id=12345, date="June 20"))
Use Python when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real Python task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.
A reliable practice flow is: create the smallest working function or script, add one normal case, add one edge case such as empty strings, spaces, and missing separators, and then confirm the result with traceback and printed inspection. If the result surprises you, reduce the code until the behavior is visible again.
The most common trap here is assuming the text has the expected length or delimiter. Avoid it by writing one sentence before the code that explains why Python is the right choice. After the code runs, verify the lesson by doing this: print both the value and its length.
Assuming the text has the expected length or delimiter.
Write the expected behavior first, then make the example prove it.
Practicing only the perfect input.
Also test empty strings, spaces, and missing separators before considering the lesson complete.
Looking only at the final output.
Trace input value and returned object through each important step.
Use it when the problem matches the behavior shown in the example and when the result can be verified through traceback and printed inspection.
Start with a tiny case, then test empty strings, spaces, and missing separators. The main warning sign is assuming the text has the expected length or delimiter.
Trace input value and returned object, predict the result, run the example, and compare your prediction with the actual output.
Explore 500+ free tutorials across 20+ languages and frameworks.