Python · Strings

Complete Guide to Python Strings

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.

1. Creating Strings

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.

2. Multi-line Strings

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)

3. Accessing Characters (Indexing)

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.

4. String Length

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.

5. String Slicing

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).

6. String Concatenation

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:

7. Repeating Strings

Use * to repeat:

print("Python " * 3)

Output:

Python Python Python

8. Common String Methods

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.

8.1 Changing Case

text = "Python"

print(text.lower())    # python
print(text.upper())    # PYTHON
print(text.title())    # Python
print(text.capitalize())

8.2 Trimming Whitespace

text = "  Python  "

print(text.strip())   # "Python"
print(text.lstrip())  # remove left spaces
print(text.rstrip())  # remove right spaces

8.3 Replacing Text

text = "I love Java"
new_text = text.replace("Java", "Python")
print(new_text)  # I love Python

8.4 Splitting a String

sentence = "Python is awesome"
words = sentence.split(" ")
print(words)

Output:

['Python', 'is', 'awesome']

8.5 Joining Strings

words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # Python is awesome

8.6 Checking Content

Add code to test:

9. String Formatting

9.1 String formatting in Python is the process of inserting variables, values, or expressions into strings to create dynamic and readable text. It allows you to build strings that adapt to data, instead of hardcoding everything..f-strings (Recommended)


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")

9.2 Using format()

print("My name is {} and I am {}".format(name, age))

9.3 Old-style % Formatting

print("My name is %s and I am %d" % (name, age))

10. Escape Characters

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.

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote
print("Hello\nWorld")
print("Tab\tSpace")

11. Checking Substrings

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.

12. Looping Through a String

You can loop through each character in a string using a for loop.

13. Comparing Strings

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..

14. Raw Strings

Raw strings ignore escape sequences. Useful for file paths and regular expressions.

15. Strings Are Immutable

You cannot change a character inside a string directly. You must create a new string instead.

❌ Wrong:

text = "Python"
text[0] = "J"  # Error

✅ Correct:

text = "Python"
text = "J" + text[1:]
print(text)  # Jython

16. Useful String Methods (Quick Reference)

MethodDescription
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

17. Real-World Example: Username Validation

Check if a username is valid (at least 4 characters, no spaces):

18. Common String Mistakes

MistakeWrongCorrect
Mixing types
"Age: " + 24
"Age: " + str(24)
Missing quotes
text = Hello
text = "Hello"
Trying to modify directly
text[0] = "X"
text = "X" + text[1:]

19. Summary

In this guide, you learned how to:

Strings are everywhere in Python. Mastering them gives you strong control over text, input, and data formatting.