In Python, a string is a sequence of characters used to represent text. Strings are used for names, messages, paths, user input, and almost everything involving text.
You can create strings with single or double quotes:
str1 = "Hello Python"
str2 = 'Welcome to coding'
Both forms are equivalent. Choose one style and stay consistent.
A multi-line string in Python is a string that spans across multiple lines of code. It’s created using triple quotes ('''...''' or """..."""). Use triple quotes for multi-line text:
text = '''This is also
a multi-line string'''
print(text)
Indexing means selecting individual characters from a string by their position. In Python, strings are sequences, so each character has an index (position number). Indexing starts at 0 for the first character.
The length of a string is the number of characters it contains (including spaces, punctuation, and special symbols).
In Python, you find it using the built-in len() function.
Slicing means extracting a portion (substring) of a string using the syntax:.Slicing lets you extract parts of a string.
Slicing is essential for parsing text (like extracting file extensions, URLs, or log entries).
It’s efficient and avoids loops.
Since you’re working on file conversion and server projects, slicing is perfect for tasks like:
Extracting a filename from a path.
Getting a domain from a URL.
Reversing strings for quick checks.
Syntax: string[start:end] (end is not included).
Concatenation means combining two or more strings into one.
In Python, this is most commonly done with the operator, but there are several other ways depending on your needs.Use + to join strings:
Use * to repeat:
print("Python " * 3)
Output:
Python Python Python
Strings have many built-in methods for common tasks. Here are some frequently used ones: In Python, common string methods are built-in functions that let you manipulate and analyze text easily. They don’t modify the original string (since strings are immutable) but instead return new values.
text = "Python"
print(text.lower()) # python
print(text.upper()) # PYTHON
print(text.title()) # Python
print(text.capitalize())
text = " Python "
print(text.strip()) # "Python"
print(text.lstrip()) # remove left spaces
print(text.rstrip()) # remove right spaces
text = "I love Java"
new_text = text.replace("Java", "Python")
print(new_text) # I love Python
sentence = "Python is awesome"
words = sentence.split(" ")
print(words)
Output:
['Python', 'is', 'awesome']
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome
Add code to test:
Purpose: To combine text with variables or expressions in a clean, structured way.
Makes code more readable and avoids messy concatenation with .
Techniques: Python supports several formatting styles, from older formatting to modern f-strings.
name = "Alex"
age = 24
print(f"My name is {name} and I am {age} years old")
format()print("My name is {} and I am {}".format(name, age))
% Formattingprint("My name is %s and I am %d" % (name, age))
An escape character is a backslash () followed by another character. • It tells Python to interpret the following character in a special way, rather than literally. • They’re used to represent things like newlines, tabs, quotes, or other non-printable characters inside strings.Escape sequences let you insert special characters.
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
print("Hello\nWorld")
print("Tab\tSpace")
Check if a substring exists within another string using the in and not in operators.
A substring is a smaller string contained within a larger string.
Checking substrings means verifying whether a piece of text exists inside another string.
Substring checks are essential for validation, parsing, and searching.
In your projects (like file conversion websites or server logs), you’ll use them to:
Verify if a filename contains a certain extension.
Check if a log entry mentions an error keyword.
Count occurrences of specific tokens in text.
You can loop through each character in a string using a for loop.
Strings in Python are compared character by character using their Unicode values. Comparisons are case-sensitive by default ( ≠ ). You can use comparison operators (, , , , , ) just like with numbers..
Raw strings ignore escape sequences. Useful for file paths and regular expressions.
You cannot change a character inside a string directly. You must create a new string instead.
text = "Python"
text[0] = "J" # Error
text = "Python"
text = "J" + text[1:]
print(text) # Jython
| Method | Description |
|---|---|
upper() | Convert to uppercase |
lower() | Convert to lowercase |
strip() | Remove surrounding spaces |
replace(a, b) | Replace a with b |
split(sep) | Split into list by separator |
join(list) | Join list into string |
find(sub) | Find index of substring, or -1 |
startswith() | Check if starts with text |
endswith() | Check if ends with text |
Check if a username is valid (at least 4 characters, no spaces):
| Mistake | Wrong | Correct |
|---|---|---|
| Mixing types | |
|
| Missing quotes | |
|
| Trying to modify directly | |
|
In this guide, you learned how to:
format()Strings are everywhere in Python. Mastering them gives you strong control over text, input, and data formatting.