
Python Course
Strings in Python
Almost every real-world program works with text. When a user logs in, their username is a string. When you receive an email, the subject and body are strings. When you search online, your query is a string. When an app shows you a notification, that message is a string.
A string in Python is simply a piece of text — any sequence of characters enclosed in quotation marks. Python provides a rich set of tools for creating, modifying, and analyzing strings, which makes it excellent for applications that process human-readable information.
Creating Strings
You create a string by enclosing text in either single quotes or double quotes. Both work the same way. You can also use triple quotes for text that spans multiple lines.
platform = "Dataplexa"
course = 'Python Programming'
message = """This is a
multi-line string."""
print(platform)
print(course)
print(message)
- Single and double quotes are interchangeable — use whichever feels clearer.
- Triple quotes (
"""or''') allow text to span multiple lines without special characters. - Strings can contain letters, numbers, spaces, punctuation, and symbols.
Accessing Individual Characters
Python treats a string as a sequence of characters. Each character has a position number called an index, starting from 0. You can access any individual character by putting its index inside square brackets.
word = "Python"
print(word[0]) # first character
print(word[1]) # second character
print(word[5]) # last character
- Counting starts at 0, not 1. So the first character is always at index 0.
- The word "Python" has 6 characters at positions 0, 1, 2, 3, 4, 5.
- Accessing an index that does not exist causes an
IndexError.
Negative Indexing
Python also allows counting from the end of a string using negative numbers. Index -1 is always the last character, -2 is second from last, and so on.
text = "Python"
print(text[-1]) # last character
print(text[-2]) # second from last
print(text[-6]) # first character
- Negative indexing is useful when you need the end of a string but do not know its length.
- A common use: checking a file extension like
filename[-4:]to get.txt.
String Slicing
Slicing lets you extract a portion of a string by specifying a start and end index. The result is a new string — the original is not changed. The format is string[start:end] where the end index is not included.
course = "PythonProgramming"
print(course[0:6]) # characters 0 to 5
print(course[6:17]) # characters 6 to 16
print(course[:6]) # from start to index 5
print(course[6:]) # from index 6 to the end
[0:6]gives characters at positions 0, 1, 2, 3, 4, 5 — position 6 is excluded.- Leaving the start empty (
[:6]) means start from the beginning. - Leaving the end empty (
[6:]) means go to the end of the string.
Measuring String Length
The built-in len() function counts the total number of characters in a string, including spaces and symbols.
name = "Dataplexa"
password = "secure123!"
print(len(name))
print(len(password))
# Validate password length
if len(password) >= 8:
print("Password length is acceptable")
len()is commonly used to validate input — checking that a username is not too short or a message is within character limits.
Built-in String Methods
Python includes many built-in methods that transform or analyze strings. A method is a function that belongs to the string and is called using a dot. Strings in Python are immutable — meaning methods do not change the original string, they return a new one.
text = "python learning"
print(text.upper()) # all uppercase
print(text.capitalize()) # first letter uppercase
print(text.title()) # each word capitalized
print(text.replace("learning", "course")) # replace a word
print(text.strip()) # remove leading/trailing spaces
print(text.count("n")) # count how many times "n" appears
upper()andlower()are used for case-insensitive comparisons — like checking if two usernames are the same regardless of how they typed it.replace()is used to clean or transform text — like removing unwanted characters.strip()removes extra spaces from both ends — very useful for cleaning user input.
Checking String Content
Python has methods that check what a string contains and return True or False.
email = "user@dataplexa.com"
number = "12345"
print(email.startswith("user")) # True
print(email.endswith(".com")) # True
print(number.isdigit()) # True — all digits
print("Python" in email) # False — not in the string
startswith()andendswith()are used for validating email formats, file extensions, and URL patterns.isdigit()checks if the string contains only numbers — useful for validating phone numbers or ID codes.
Splitting and Joining Strings
split() breaks a string into a list of parts. join() combines a list of strings back into one string. These two methods are used constantly in data processing.
sentence = "Python is easy to learn"
# Split into a list of words
words = sentence.split(" ")
print(words)
# Join the list back into a string
joined = "-".join(words)
print(joined)
split()is used to break CSV data, parse commands, or extract parts of a URL.join()is used to build formatted output from a list of values.
Combining Strings with Concatenation
You can join two or more strings together using the + operator. This is called concatenation.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
- The
+operator joins strings, not numbers. You cannot concatenate a string directly with a number — you must convert the number to a string first usingstr().
F-Strings — The Modern Way to Format Text
F-strings (formatted string literals) are the clearest and most modern way to embed variables directly inside a string. Add an f before the opening quote, then put variable names inside curly braces {}.
name = "Alex"
score = 95
grade = "A"
print(f"Student: {name}")
print(f"Score: {score} — Grade: {grade}")
print(f"Well done {name}, you passed with an {grade}!")
- F-strings are faster and easier to read than concatenation.
- You can put any expression inside
{}— not just variable names. - F-strings were introduced in Python 3.6 and are now the preferred way to build text output in professional Python code.
Real World Example — User Welcome Message
This example combines several string techniques to build a clean, professional welcome message for a logged-in user.
username = " john_doe "
platform = "Dataplexa"
# Clean the username first
clean_name = username.strip()
# Build the welcome message
message = f"Welcome back, {clean_name.title()}!"
info = f"You are now logged into {platform}."
print(message)
print(info)
print(f"Username length: {len(clean_name)} characters")
strip()removes the extra spaces the user accidentally typed around their name.title()capitalizes the first letter of each word for a polished display.- The f-string puts everything together cleanly in one readable line.
Strings Are Immutable
One important thing to know: strings in Python cannot be changed after they are created. This is called being immutable. When you call a method like upper() or replace(), Python creates a new string — it does not modify the original.
original = "hello"
modified = original.upper()
print(original) # still lowercase — unchanged
print(modified) # new string in uppercase
- If you want to "change" a string, you save the result of the method into a new variable (or the same one).
- Immutability makes strings safe to share across a program without unexpected changes.
Practice
What index position does the first character of a string always have?
Which built-in function counts the number of characters in a string?
Strings in Python cannot be changed after creation. What word describes this property?
Which string method breaks a string into a list of parts?
Quick Quiz
Extracting a portion of a string using a start and end index is called what?
Which technique embeds variables directly inside a string using curly braces?
Which index gives you the last character of a string?