Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Basics of Strings

Python Strings Basics - Complete Guide

Learn the fundamentals of strings in Python — the building blocks of text processing.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What Are Strings?
  • Creating Strings
  • String Indexing
  • String Slicing
  • String Concatenation
  • String Repetition
  • String Immutability
  • Escape Sequences
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What are strings — understanding text data in Python
  • Creating strings — using quotes and different methods
  • String indexing — accessing individual characters
  • String slicing — extracting portions of text
  • String operations — concatenation, repetition, and more
  • Immutability — why strings can't be changed in place

What Are Strings?

In Python, a string is simply a piece of text. It could be a single letter, a word, a sentence, or even an entire book. Strings are how we work with text in programming — from user input to file content to API responses.

Think of a string like a necklace made of beads. Each bead is a character — a letter, number, space, or symbol. The whole necklace is the string, and the beads are in a specific order. Python gives you tools to examine, rearrange, and work with these beads.

💡 Key concept: Strings are one of the most important data types in Python. Almost every program you write will use strings in some way — for output, user input, data processing, and much more.

Creating Strings

1

Ways to Create Strings

# Strings can be created in several ways

# 1. Using single quotes
name = 'Alice'
greeting = 'Hello, World!'
print(greeting)  # Hello, World!

# 2. Using double quotes
message = "Python is awesome"
print(message)  # Python is awesome

# 3. Single quotes vs double quotes
# You can use either, but be consistent
# Use double quotes when your string contains single quotes:
text = "It's a beautiful day"
print(text)  # It's a beautiful day

# Use single quotes when your string contains double quotes:
quote = 'She said, "Hello!"'
print(quote)  # She said, "Hello!"

# 4. Triple quotes for multi-line strings
long_text = """This is a multi-line string.
It can span multiple lines.
You can write paragraphs in it."""
print(long_text)

# 5. Triple quotes with single quotes work too
another_text = '''This is also a multi-line string.
It works the same way.'''

# 6. Creating empty strings
empty1 = ''
empty2 = ""
empty3 = str()  # Using the str() function
print(empty1)  # (nothing prints)

# 7. Converting other types to strings
age = 25
age_str = str(age)
print(f"Age as string: {age_str}")
print(f"Type: {type(age_str)}")

Creating strings key points:

  • Quotes — single, double, or triple for multi-line
  • Consistency — pick a style and stick with it
  • str() — convert numbers and other types to strings
  • Empty strings — useful as placeholders

Quick Check: What type of quotes would you use for a multi-line string? (Answer: Triple quotes)

String Indexing

2

Accessing Individual Characters

# Each character in a string has an index (position)

word = "Python"

# 1. Positive indexing (starts from 0)
print(word[0])  # P
print(word[1])  # y
print(word[2])  # t
print(word[3])  # h
print(word[4])  # o
print(word[5])  # n

# 2. Negative indexing (starts from -1 from the end)
print(word[-1])  # n
print(word[-2])  # o
print(word[-3])  # h
print(word[-4])  # t
print(word[-5])  # y
print(word[-6])  # P

# 3. Getting the length of a string
length = len(word)
print(f"Length of '{word}': {length}")  # 6

# 4. Accessing the last character
last_char = word[-1]  # or word[len(word)-1]
print(f"Last character: {last_char}")

# 5. Trying to access an index that doesn't exist
# print(word[10])  # This will cause an IndexError

# 6. Strings are sequences - you can check if a character exists
if 'P' in word:
    print("'P' is in the string")

Indexing key points:

  • Positive indices — start at 0 for the first character
  • Negative indices — start at -1 for the last character
  • len() — get the number of characters
  • IndexError — happens when you access an index that doesn't exist

Quick Check: What is the index of the first character in a string? (Answer: 0)

String Slicing

3

Extracting Parts of a String

# Slicing lets you extract a portion of a string
# Syntax: string[start:end:step]

text = "Python Programming"

# 1. Basic slicing
print(text[0:6])   # Python (characters from index 0 to 5)
print(text[7:18])  # Programming (index 7 to 17)
print(text[:6])    # Python (from beginning to index 5)
print(text[7:])    # Programming (from index 7 to end)
print(text[:])     # Python Programming (entire string)

# 2. Slicing with negative indices
print(text[-11:])  # Programming (from -11 to end)
print(text[-6:-1])  # rammi (last 5 characters except the last)

# 3. Slicing with step
word = "abcdefghij"
print(word[::2])   # acegi (every second character)
print(word[1::2])  # bdfhj (every second character starting from index 1)
print(word[::-1])  # jihgfedcba (reverses the string)

# 4. Practical examples
name = "Alice Johnson"
first_name = name[:5]
last_name = name[6:]
print(f"First name: {first_name}")  # Alice
print(f"Last name: {last_name}")    # Johnson

# 5. Slicing to get a substring
email = "user@example.com"
username = email[:email.index('@')]
domain = email[email.index('@')+1:]
print(f"Username: {username}")  # user
print(f"Domain: {domain}")      # example.com

Slicing key points:

  • Start — the index to begin (inclusive)
  • End — the index to stop (exclusive)
  • Step — how many characters to skip
  • Negative step — reverses the string
  • Omitted values — default to beginning, end, or 1

Quick Check: How do you reverse a string using slicing? (Answer: string[::-1])

String Concatenation

4

Joining Strings Together

# Concatenation means joining strings together

# 1. Using the + operator
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name
print(full_name)  # Alice Johnson

# 2. Joining multiple strings
greeting = "Hello"
name = "Bob"
message = greeting + ", " + name + "!"
print(message)  # Hello, Bob!

# 3. Concatenating string literals
# Python automatically concatenates adjacent string literals
text = "Hello" " " "World"
print(text)  # Hello World

# 4. Using join() method (more efficient for many strings)
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # Python is awesome

# 5. Concatenating numbers (must convert to string first)
age = 25
message = "I am " + str(age) + " years old"
print(message)  # I am 25 years old

# 6. Using f-strings (Python 3.6+)
name = "Charlie"
age = 30
message = f"{name} is {age} years old"
print(message)  # Charlie is 30 years old

Concatenation key points:

  • + operator — join strings together
  • join() — efficient for joining many strings
  • str() — convert numbers to strings
  • f-strings — modern and readable

Quick Check: Which method is more efficient for joining many strings? (Answer: join())

String Repetition

5

Repeating Strings

# The * operator repeats strings

# 1. Basic repetition
text = "Ha"
print(text * 3)  # HaHaHa

# 2. Creating a line
line = "-" * 40
print(line)
print("Header")
print(line)

# 3. Creating a pattern
pattern = "* " * 10
print(pattern)  # * * * * * * * * * *

# 4. Repeating with variables
count = 5
print("Hello " * count)  # Hello Hello Hello Hello Hello

# 5. Repeating zero times gives an empty string
print("Test" * 0)  # (nothing prints)

# 6. Repeating with user input
# num = int(input("How many times? "))
# print("Yes! " * num)

# 7. Creating a simple progress bar
def progress_bar(percentage):
    filled = "█" * (percentage // 10)
    empty = "░" * (10 - (percentage // 10))
    return f"{filled}{empty} {percentage}%"

print(progress_bar(30))  # ███░░░░░░░ 30%
print(progress_bar(75))  # ███████░░░ 75%

Repetition key points:

  • * operator — repeats a string
  • Integer value — must be a whole number
  • Zero repetitions — gives an empty string
  • Useful for — creating lines, patterns, progress bars

Quick Check: What operator is used to repeat a string? (Answer: *)

String Immutability

6

Why Strings Can't Be Changed In Place

# Strings in Python are immutable — they cannot be changed after creation

text = "Hello"

# 1. Trying to change a character directly (this doesn't work)
# text[0] = "J"  # This will cause a TypeError

# 2. Instead, you create a new string
new_text = "J" + text[1:]
print(new_text)  # Jello

# 3. Converting to a list (mutable), changing, then back to string
text_list = list("Hello")
text_list[0] = "J"
new_text = "".join(text_list)
print(new_text)  # Jello

# 4. Many string methods return new strings
original = "python"
upper_version = original.upper()
print(original)     # python (unchanged)
print(upper_version) # PYTHON (new string)

# 5. Memory efficiency
# Python reuses strings when possible
a = "hello"
b = "hello"
print(a is b)  # True (same object in memory)

# 6. Each modification creates a new string
text = "Hello"
text = text + " World"  # Creates a new string, old one is garbage collected

Immutability key points:

  • Cannot change in place — strings are read-only after creation
  • New strings — operations create new strings
  • Memory efficient — Python reuses string objects when possible
  • List conversion — convert to list for modifications

Quick Check: Can you change a string after it's created? (Answer: No, strings are immutable)

Escape Sequences

7

Special Characters in Strings

# Escape sequences let you include special characters in strings

# 1. Newline (\n)
print("Hello\nWorld")
# Hello
# World

# 2. Tab (\t)
print("Name:\tAlice")
print("Age:\t25")
# Name:   Alice
# Age:    25

# 3. Backslash (\\)
print("C:\\Users\\Documents")
# C:\Users\Documents

# 4. Single quote (\')
print("It\'s a beautiful day")
# It's a beautiful day

# 5. Double quote (\")
print("She said, \"Hello!\"")
# She said, "Hello!"

# 6. Raw strings (ignore escape sequences)
path = r"C:\Users\Documents\file.txt"
print(path)  # C:\Users\Documents\file.txt

# 7. Unicode characters
print("\u263A")  # ☺
print("\u2764")  # ❤

# 8. Combining escape sequences
print("Line1\nLine2\nLine3")
print("Column1\tColumn2\tColumn3")

Escape sequences key points:

  • \n — new line
  • \t — tab
  • \\ — backslash
  • \' — single quote
  • \" — double quote
  • r"..." — raw strings ignore escapes

Quick Check: What escape sequence creates a new line? (Answer: \n)

Try It Yourself

Experiment with strings in the editor below. Try creating, indexing, and slicing strings.

Loading Pyodide... 0%
Python Code Editor
========================================
STRINGS BASICS PRACTICE
========================================

1. CREATING STRINGS
Hello, World!
Alice

2. STRING INDEXING
First character: P
Last character: n
Length: 6

3. STRING SLICING
First 4 characters: Prog
Last 4 characters: ming
Every second character: Pormn
Reversed: gnimmargorP

4. STRING CONCATENATION
Full name: John Doe

5. STRING REPETITION
--------------------
PythonPythonPython

6. ESCAPE SEQUENCES
Line 1
Line 2
Column 1 Column 2

Strings basics practice complete!
🏆

You've Got It!

You now understand the basics of strings in Python — creating them, accessing characters, slicing, and common operations. This is the foundation for all string work!

Quick Quiz

Test what you've learned:

1. What is the index of the first character in a string?
2. How do you get the last character of a string?
3. What does string[::-1] do?
4. Which escape sequence creates a new line?
5. Why can't you change a string in place?

Frequently Asked Questions

What is the difference between single and double quotes? ▼

There is no functional difference. You can use either. The main reason to choose one over the other is to avoid escaping quotes inside the string. Use double quotes if your string contains single quotes, and vice versa.

What is the difference between indexing and slicing? ▼

Indexing gets a single character at a specific position (e.g., word[2]). Slicing extracts a portion of the string (e.g., word[2:5]). Indexing returns a string of length 1, while slicing returns a string of any length.

Why are strings immutable in Python? ▼

Immutability makes strings safer and more efficient. It allows Python to reuse string objects, which saves memory. It also prevents accidental changes to strings, making code more predictable and easier to debug.

What's a common interview question about strings? ▼

Common questions include: "Explain string immutability," "How do you reverse a string in Python?" and "What is the difference between indexing and slicing?"

Can I use spaces in strings? ▼

Yes! Strings can contain any characters, including spaces. They are just like any other character in the string.

How do I convert a number to a string? ▼

Use the str() function: age_str = str(25). This converts any number to its string representation so you can concatenate it with other strings.

Where to Go From Here

Now that you understand string basics, check out these related topics:

String Special Operators

Learn about operators like %, in, and more for strings.

Learn More →

String Formatting

Master different ways to format strings in Python.

Learn More →

String Methods

Explore Python's powerful string methods.

Learn More →
Interview Resources
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: 📝 File Handling Assignments Next: String Special Operators →