Python Strings – A Complete Guide for Beginners (with Examples)
Python Strings – A Complete Guide for Beginners (with Examples)
Published on Code with Py | Category: Python Basics | Reading time: ~12 min
Strings are one of the most used data types in Python. Whether you are building a web application, processing user input, or working with files — strings are everywhere. In this guide, you will learn everything about Python strings from the basics to advanced string methods, with clear code examples and outputs.
Table of Contents
- What is a String in Python?
- How to Create Strings
- Accessing Characters – Indexing
- String Slicing
- String Immutability
- String Concatenation and Repetition
- String Formatting (f-strings, format())
- Important String Methods
- String Operations – Checking and Searching
- Escape Characters
- Multi-line Strings
- Real-life Mini Projects
- FAQ
1. What is a String in Python?
A string in Python is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Each character in a string has a position called an index.
In Python, strings belong to the str data type. They can contain letters, numbers, spaces, and special symbols.
name = "Python" print(type(name))
Output: <class 'str'>
2. How to Create Strings
Python gives you three ways to create a string. All three are valid and commonly used.
# Single quotes s1 = 'Hello, World!' # Double quotes s2 = "Hello, Python!" # Triple quotes (for multi-line) s3 = """This is a multi-line string""" print(s1) print(s2) print(s3)
Hello, World! Hello, Python! This is a multi-line string
Tip: Use double quotes when your string contains an apostrophe. Example: "It's a great day" — this avoids errors.
3. Accessing Characters – String Indexing
Every character in a string has an index number. Python indexing starts from 0. You can also use negative indexing to access characters from the end of the string.
name = "Python" print(name[0]) # First character print(name[3]) # Fourth character print(name[-1]) # Last character print(name[-2]) # Second last character
P h n o
Here is how the indexing works for the word "Python":
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
4. String Slicing
Slicing allows you to extract a part of a string. The syntax is: string[start:stop:step]
text = "Hello, Python!" print(text[0:5]) # Hello print(text[7:]) # Python! print(text[:5]) # Hello print(text[::2]) # Every second character print(text[::-1]) # Reverse the string
Hello Python! Hello Hlo yhn !nohtyP ,olleH
Tip: text[::-1] is the most popular way to reverse a string in Python. It is commonly asked in coding interviews!
5. String Immutability
Strings in Python are immutable. This means once a string is created, you cannot change its individual characters. If you try to do so, Python will raise a TypeError.
name = "Python" name[0] = "J" # This will cause an error
TypeError: 'str' object does not support item assignment
Note: You cannot modify a string directly. Instead, create a new string using concatenation or string methods.
6. String Concatenation and Repetition
You can combine two strings using the + operator (concatenation) and repeat a string using the * operator.
first = "Hello" second = " World" print(first + second) # Concatenation print(first * 3) # Repetition
Hello World HelloHelloHello
7. String Formatting
Python provides powerful ways to format strings. The most modern and recommended method is f-strings (available from Python 3.6+).
Method 1 – f-strings (Recommended)
name = "Raju" age = 22 print(f"My name is {name} and I am {age} years old.")
My name is Raju and I am 22 years old.
Method 2 – format() method
print("My name is {} and I am {} years old.".format("Raju", 22))
My name is Raju and I am 22 years old.
Method 3 – % operator (Old style)
print("My name is %s and I am %d years old." % ("Raju", 22))
My name is Raju and I am 22 years old.
8. Important String Methods
Python has a rich set of built-in string methods. Here are the most commonly used ones with examples:
| Method | What it does | Example |
|---|---|---|
upper() | Converts to uppercase | "hello".upper() → "HELLO" |
lower() | Converts to lowercase | "HELLO".lower() → "hello" |
strip() | Removes spaces from both ends | " hi ".strip() → "hi" |
replace() | Replaces a part of string | "cat".replace("c","b") → "bat" |
split() | Splits string into a list | "a,b,c".split(",") → ['a','b','c'] |
join() | Joins list items into string | "-".join(['a','b']) → "a-b" |
find() | Finds index of substring | "hello".find("l") → 2 |
count() | Counts occurrences | "banana".count("a") → 3 |
startswith() | Checks start of string | "Python".startswith("P") → True |
endswith() | Checks end of string | "Python".endswith("n") → True |
capitalize() | Capitalizes first letter | "python".capitalize() → "Python" |
title() | Capitalizes each word | "hello world".title() → "Hello World" |
len() | Returns length of string | len("Hello") → 5 |
Code examples for key methods
text = " Hello, Python World! " print(text.strip()) print(text.lower()) print(text.upper()) print(text.replace("Python", "Code")) print(text.split(","))
Hello, Python World! hello, python world! HELLO, PYTHON WORLD! Hello, Code World! [' Hello', ' Python World! ']
9. Checking and Searching in Strings
You can check whether something exists in a string using the in and not in keywords.
sentence = "I am learning Python programming" print("Python" in sentence) print("Java" not in sentence) print(sentence.count("a")) print(sentence.find("Python"))
True True 3 14
10. Escape Characters
Escape characters allow you to include special characters inside a string that would otherwise cause errors.
| Escape Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab space |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
print("Hello\nWorld") print("Name:\tPython") print("She said \"Hello\"")
Hello World Name: Python She said "Hello"
11. Multi-line Strings
Use triple quotes to write strings that span multiple lines. This is useful for writing long messages, paragraphs, or SQL queries.
message = """Dear Student, Welcome to Code with Py. Today we are learning Python Strings. Happy Learning!""" print(message)
Dear Student, Welcome to Code with Py. Today we are learning Python Strings. Happy Learning!
12. Real-life Mini Projects Using Strings
Project 1 – Username Validator
username = input("Enter username: ") if username.isalnum(): print("Valid username!") else: print("Invalid! Use letters and numbers only.")
Project 2 – Palindrome Checker
word = input("Enter a word: ").lower() if word == word[::-1]: print(f"{word} is a palindrome!") else: print(f"{word} is not a palindrome.")
Project 3 – Word Counter
sentence = input("Enter a sentence: ") words = sentence.split() print(f"Total words: {len(words)}")
- Strings are sequences of characters enclosed in quotes
- Indexing starts from 0; negative indexing starts from -1
- Slicing extracts parts of a string using start:stop:step
- Strings are immutable — they cannot be changed after creation
- f-strings are the best way to format strings in Python 3.6+
- Python has 40+ built-in string methods for every operation you need
Frequently Asked Questions (FAQ)
Q1. What is a string in Python?
A string in Python is a sequence of characters enclosed in single, double, or triple quotes. It belongs to the str data type.
Q2. Are strings mutable in Python?
No. Strings are immutable in Python. Once created, individual characters cannot be changed. You must create a new string instead.
Q3. How do you reverse a string in Python?
Use slicing: text[::-1]. This is the most Pythonic and efficient way to reverse a string.
Q4. What is the difference between find() and index()?
Both find the position of a substring. But find() returns -1 if not found, while index() raises a ValueError.
Q5. How do you check if a string contains only digits?
Use the isdigit() method. It returns True if all characters in the string are digits, otherwise False.
If this post helped you, share it with your friends who are learning Python. Drop your questions in the comments below — happy to help!
Comments
Post a Comment