Python November 01 ,2025

Strings in Python —

 

Table of Content-

  1. What is a String?
  2. How to Create Strings
  3. Strings as Sequences (Indexing and Slicing)
  4. Strings are Immutable
  5. String Operations
  6. Concatenation (+)
  7. Repetition (*)
  8. Length of a String (len())
  9. Common String Methods
  10. Escape Sequences
  11. Raw Strings
  12. String Formatting
  13. String Comparison
  14. Iterating Over Strings
  15. Membership Operators (in / not in)
  16. String Translation
  17. Strings and Memory (Interning)
  18. Example: Putting It All Together

1. What is a String?

A string in Python is a sequence of characters — such as letters, numbers, symbols, or spaces — enclosed within quotes.
Strings are used to store textual data, like names, messages, file paths, or any text input.

Every element (character) in a string has a position or index.
The first character starts at index 0, and indexing continues sequentially.

Example

name = "Python"

Here,

  • 'P' is at index 0
  • 'y' is at index 1
  • 'n' is at index 5

Python reads a string as an ordered collection of characters.

2. How to Create Strings

Python allows you to create strings using single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).

Single and Double Quotes

Both work the same way. Using double quotes allows you to include single quotes inside easily, and vice versa.

str1 = 'Hello World'
str2 = "Python Programming"

Triple Quotes

Triple quotes are used to create multi-line strings or docstrings.
They can span multiple lines and preserve line breaks.

str3 = '''This is
a multi-line
string example.'''
print(str3)

Output:

This is
a multi-line
string example.

3. Strings as Sequences (Indexing and Slicing)

Since strings are sequences, we can access individual characters or extract parts of them.

Indexing

Every character in a string has a position (index).

  • Positive indexing starts from 0 (left to right).
  • Negative indexing starts from -1 (right to left).

For example:

word = "Python"
CharacterPython
Positive Index012345
Negative Index-6-5-4-3-2-1

Examples:

print(word[0])   # P
print(word[-1])  # n
print(word[2])   # t

Slicing

Slicing is a powerful feature in Python that allows you to extract a specific portion (or "slice") of a sequence type — such as a string, list, tuple, or any other sequence — without modifying the original data.

In simple terms, slicing means selecting a range of elements from a sequence using a defined start index, end index, and an optional step value

Slicing extracts a part (substring) of the original string.
Syntax:

string[start:end:step]
  • start → index to begin (inclusive)
  • end → index to stop (exclusive)
  • step → number of characters to skip between each

Example:

s = "PythonProgramming"
print(s[0:6])     # 'Python'
print(s[6:])      # 'Programming'
print(s[:6])      # same as s[0:6]
print(s[::2])     # every 2nd character → 'Pto rgamn'
print(s[::-1])    # reverse the string → 'gnimmargorPnohtyP'

The [::-1] trick is commonly used to reverse strings.

4. Strings are Immutable

One of the most important properties of Python strings is that they are immutable.
This means once a string is created, you cannot change its characters.
If you try to modify a character, Python will throw an error.

Example

s = "Hello"
# Trying to change the first letter
s[0] = 'Y'    # ❌ Error

Output:

TypeError: 'str' object does not support item assignment

However, you can reassign a new string to the same variable:

s = "Hello"
s = "Yellow"  # ✅ Creates a new string object

5. String Operations

  1. Concatenation (+)
  2. Repetition (*)
  3. Length of String
  4. Common String Methods — grouped and deeply explained.

1. Concatenation (+ Operator)

Concept:
Concatenation means joining two or more strings together to form a single continuous string.
In Python, you can use the + operator to combine strings. Since strings are immutable, this operation doesn’t modify the existing strings; instead, it creates a new string in memory.

Syntax:

new_string = string1 + string2

Explanation:
When Python sees the + operator between strings, it appends the contents of the right-hand string to the left-hand string and returns a new string. You can also include spaces, punctuation, or variables to format text neatly.

Example:

a = "Smart"
b = "Home"
c = a + " " + b
print(c)

Output:

Smart Home

Detailed Explanation:
Here, three parts are combined:

  • a = "Smart"
  • " " = space between words
  • b = "Home"
    The new string "Smart Home" is created, leaving the original variables a and b unchanged.

Practical Use:

  • Creating full names: full_name = first_name + " " + last_name
  • Constructing file paths or URLs dynamically.

2. Repetition (* Operator)

Concept:
Repetition means duplicating a string multiple times using the * operator. This is particularly useful when you need to repeat characters, create separators, or display formatted output.

Syntax:

repeated_string = original_string * n

Explanation:
Here, n is an integer specifying how many times the string should be repeated. Like concatenation, repetition creates a new string.

Example:

s = "Hi "
print(s * 3)

Output:

Hi Hi Hi 

Detailed Explanation:
The string "Hi " is repeated 3 times and joined together. Each repetition keeps the exact characters and spaces as in the original.

Practical Use:

  • Creating repeated patterns (e.g., "=" * 40 for console formatting)
  • Mock data generation (e.g., "abc" * 5 → "abcabcabcabcabc")

3. Length of a String (len() Function)

Concept:
The len() function in Python returns the number of characters present in a string, including letters, digits, spaces, and special characters.

Syntax:

length = len(string)

Example:

s = "Python"
print(len(s))

Output:

6

Detailed Explanation:
The string "Python" contains six characters: P, y, t, h, o, n.
Even spaces and punctuation marks are counted.

Example:

text = "Hello World!"
print(len(text))  # 12 (includes space and exclamation)

Practical Use:

  • Validating password length.
  • Ensuring strings fit within a specific size limit.
  • Counting characters in text data.

4. Common String Methods 

Python provides several built-in string methods for performing operations like changing case, trimming spaces, searching text, splitting, joining, and validation.

Let’s study them category-wise.

A. Changing Case

Case conversion methods are used to change the letter casing of strings.
They are primarily useful for:

  • Normalizing user input (e.g., converting all text to lowercase before comparison)
  • Formatting display text (like titles, headings, etc.)
  • Ensuring consistency in databases or file systems.

Example Code:

text = "python programming"

print(text.upper())       # Converts all letters to uppercase
print(text.lower())       # Converts all letters to lowercase
print(text.title())       # Capitalizes the first letter of every word
print(text.capitalize())  # Capitalizes the first character of the string
print(text.swapcase())    # Converts uppercase → lowercase and vice versa

Output:

PYTHON PROGRAMMING
python programming
Python Programming
Python programming
PYTHON PROGRAMMING

Explanation:

  • upper() – Helpful for case-insensitive comparison.
  • lower() – Used before validation to ignore user typing variations.
  • title() – Useful for names, titles, or headlines.
  • capitalize() – Used in sentences (only first letter capitalized).
  • swapcase() – Inverts letter casing, often for stylistic purposes.

B. Removing Whitespace

Concept:
Whitespace includes spaces, tabs (\t), and newline characters (\n). Often, data read from files or user input contains unwanted spaces — these methods clean them.

Example:

s = "   Hello World   "
print(s.strip())   # Removes from both ends
print(s.lstrip())  # Removes only from the left
print(s.rstrip())  # Removes only from the right

Output:

Hello World
Hello World   
   Hello World

Explanation:

  • strip() → removes whitespace from both sides.
  • lstrip() → removes whitespace only on the left side.
  • rstrip() → removes whitespace only on the right side.

Practical Use:
When reading data from files or user input (e.g., form data, CSVs), stripping helps clean unwanted formatting.

C. Finding and Replacing Text

find() Method

Concept:
Used to search for a substring inside a string and return its starting index.
If the substring doesn’t exist, it returns -1.

Example:

s = "I love Python programming"
print(s.find("Python"))  # 7
print(s.find("Java"))    # -1

Explanation:
The substring "Python" starts at index 7 (counting from 0).
If the word isn’t found, find() returns -1.

replace() Method

Concept:
Used to replace all occurrences of a substring with another substring.

Example:

s = "I love Python programming"
new_s = s.replace("Python", "Java")
print(new_s)

Output:

I love Java programming

Practical Use:

  • Replacing incorrect data or typos.
  • Censoring words (e.g., "badword".replace("badword", "***")).

D. Splitting and Joining Strings

Splitting (split())

Concept:
Divides a string into a list of substrings based on a specified delimiter (default: space).

Example:

text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits)

Output:

['apple', 'banana', 'cherry']

Explanation:
Here, the string is broken into parts at every comma. Useful when processing CSV or log data.

Joining (join())

Concept:
Performs the reverse of splitting — combines a list of strings into a single string, inserting a chosen separator between them.

Example:

words = ["I", "love", "Python"]
sentence = " ".join(words)
print(sentence)

Output:

I love Python

Explanation:
The " ".join() method uses a space as a separator between elements of the list.

Practical Use:

  • Reconstructing sentences.
  • Formatting CSV lines from lists.

E. Checking String Properties

Concept:
Python strings offer several methods that check the type or format of the text.
Each returns a Boolean (True or False).

Example:

s = "Python123"

print(s.isalpha())   # Checks if all characters are alphabets
print(s.isdigit())   # Checks if all characters are digits
print(s.isalnum())   # Checks if characters are alphabets or digits
print(s.islower())   # Checks if all letters are lowercase
print(s.isupper())   # Checks if all letters are uppercase
print(s.startswith("Py"))  # Checks if string starts with 'Py'
print(s.endswith("on"))    # Checks if string ends with 'on'

Output:

False
False
True
False
False
True
True

Explanation:

  • isalpha() → returns True only if all characters are alphabets.
  • isdigit() → True if all characters are numeric digits.
  • isalnum() → True if string has only alphabets and/or digits.
  • islower() / isupper() → checks the case.
  • startswith() / endswith() → useful for filtering filenames, URLs, or logs.

8. Escape Sequences

Escape sequences allow you to use characters in strings that are otherwise difficult to type (like newlines, quotes, tabs).

SequenceMeaningExample
\'Single quote'It\'s good' → It's good
\"Double quote"He said \"Hello\""
\\Backslash'C:\\path' → C:\path
\nNew line"Hello\nWorld" → two lines
\tTab"Hello\tWorld" → adds space
\bBackspace"Hello\bWorld"

Example:

print("Hello\nWorld")
print("He said \"Python is fun!\"")

Output:

Hello
World
He said "Python is fun!"

9. Raw Strings

If you don’t want escape sequences to be interpreted, prefix the string with r or R.

path = r"C:\Users\Saumya\Documents"
print(path)

Output:

C:\Users\Saumya\Documents

The backslashes are preserved exactly as written.

10. String Formatting

String formatting means inserting variables, values, or expressions inside strings dynamically — without manually concatenating them using the + operator.

It allows you to create readable and professional-looking text output, especially useful when generating reports, messages, or displaying results in programs.

For example, instead of writing:

print("My name is " + name + " and I am " + str(age) + " years old.")

you can use formatting to make it simpler and cleaner.

Python provides three main techniques for string formatting:

  1. str.format() method
  2. f-strings (modern and recommended)
  3. % formatting (older style)

Let’s discuss each in detail.

A. Using format() Method

Concept

The format() method allows you to insert variables into placeholders {} inside a string.
When Python executes the code, it replaces the {} with the corresponding values provided inside .format().

Example 1: Basic Usage

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:

My name is Alice and I am 25 years old.

Explanation:

  • {} acts as a placeholder for variables.
  • The first {} is replaced by the first argument in .format(), and the second {} by the second argument.

Example 2: Positional Indexing

You can specify the position numbers inside the placeholders to control the order:

print("Name: {0}, Age: {1}".format(name, age))
print("Age: {1}, Name: {0}".format(name, age))

Output:

Name: Alice, Age: 25
Age: 25, Name: Alice

Explanation:

  • {0} corresponds to the first argument (name).
  • {1} corresponds to the second argument (age).
  • This allows you to reuse or reorder values in complex strings.

Example 3: Keyword Arguments

You can also pass named parameters to .format():

print("Name: {n}, Age: {a}".format(n="Alice", a=25))

Output:

Name: Alice, Age: 25

Explanation:
Using keyword arguments makes the code more readable and less error-prone.

Practical Uses

  • Useful in generating formatted reports or print statements.
  • Handy when working with multiple variables in templates.
  • Commonly used in logging, file writing, and data formatting.

B. Using f-Strings (Formatted String Literals)

Concept

f-Strings (introduced in Python 3.6) are the most modern and efficient way to format strings.
They make the code cleaner, faster, and easier to read.

When you prefix a string with f or F, Python allows you to insert variables or expressions directly inside curly braces {}.

Example 1: Basic Usage

name = "Bob"
score = 95
print(f"Student {name} scored {score} marks.")

Output:

Student Bob scored 95 marks.

Explanation:

  • Any variable inside {} is automatically replaced by its value.
  • No need for .format() or %.

Example 2: Using Expressions

You can even perform calculations or function calls inside {}:

a, b = 10, 20
print(f"Sum of {a} and {b} is {a + b}")

Output:

Sum of 10 and 20 is 30

Explanation:

  • f-strings are evaluated at runtime, so Python executes the expression inside {} before printing.

Example 3: Formatting Numbers

You can format numbers within f-strings (useful for currency, percentages, or decimals):

price = 49.5678
print(f"Price: ₹{price:.2f}")

Output:

Price: ₹49.57

Explanation:

  • .2f means “format as a float with 2 decimal places”.

Advantages of f-Strings

✅ Clean and readable syntax
✅ Fastest among all formatting methods
✅ Supports expressions and function calls
✅ Easy to use for numbers, dates, and special formatting

 

C. Using % Formatting (Old Style)

Concept

Before format() and f-strings were introduced, Python used the C-style (%) formatting, similar to how formatting works in C programming.

This method uses format specifiers like %s, %d, %f, etc., to indicate the type of data being inserted.

Example 1: Basic Usage

name = "Charlie"
age = 30
print("My name is %s and I am %d years old." % (name, age))

Output:

My name is Charlie and I am 30 years old.

Explanation:

  • %s → string
  • %d → integer
  • %f → float
  • The variables are passed as a tuple (name, age) after the % symbol.

Example 2: Formatting Numbers

pi = 3.1415926
print("Value of pi: %.2f" % pi)

Output:

Value of pi: 3.14

Explanation:

  • %.2f means “float with 2 decimal places”.

Example 3: Mixing Data Types

name = "Alice"
marks = 89.5
subject = "Maths"
print("%s scored %.1f marks in %s." % (name, marks, subject))

Output:

Alice scored 89.5 marks in Maths.

Drawbacks of % Formatting

❌ Less readable with many variables
❌ Can cause type errors if specifiers don’t match data types
❌ Outdated (mostly replaced by format() and f-strings)

Comparison of All Three Methods

Feature% Formattingstr.format()f-Strings
Introduced InEarly Python versionsPython 2.6+Python 3.6+
Syntax SimplicityModerateVerboseSimplest
ReadabilityAverageGoodExcellent
PerformanceSlowModerateFastest
Supports Expressions❌ No❌ Limited✅ Yes
Best ForLegacy codeCompatibilityModern Python

 

11. String Comparison

Python compares strings lexicographically, meaning it uses the ASCII (Unicode) value of each character.

print("apple" == "apple")   # True
print("apple" < "banana")   # True ('a' < 'b')
print("Apple" < "apple")    # True ('A' < 'a' in ASCII)

Uppercase letters are considered smaller than lowercase letters.

12. Iterating Over Strings

Concept

Strings in Python are iterable sequences, meaning each character in a string can be accessed one by one using loops — especially the for loop.
Iteration is useful for performing operations like character counting, searching, validation, or transformation.

A. Simple Iteration

You can iterate through each character in a string directly:

for ch in "Python":
    print(ch)

Output:

P
y
t
h
o
n

Explanation:

  • The loop runs once for each character.
  • The variable ch takes the value of each character sequentially.

B. Iterating with Index (Using enumerate())

If you want both the index position and the character, use enumerate():

for index, ch in enumerate("Python"):
    print(index, ch)

Output:

0 P
1 y
2 t
3 h
4 o
5 n

Explanation:

  • enumerate() returns both the index and the corresponding character.
  • This is very useful when you need the position of each character.

Practical Uses

✅ Checking or modifying characters one by one.
✅ Searching for specific letters or digits in text.
✅ Building new strings or applying encryption (e.g., Caesar cipher).
✅ Useful in text analysis and parsing.

13. Membership Operators

Concept

Python provides two membership operators — in and not in — to check whether a substring or character exists within a string.

They return Boolean values (True or False).

Example

s = "Python programming"
print("Python" in s)      # True
print("Java" not in s)    # True

Explanation:

  • "Python" in s → Checks if the substring "Python" exists in the string s.
  • "Java" not in s → Checks if "Java" does not exist in the string.

Practical Uses

✅ Searching keywords within sentences or files.
✅ Filtering text data.
✅ Checking login credentials, email domains, or file extensions.
✅ Useful in conditional statements for decision-making.

Example: Conditional Use

if "admin" in email:
    print("Admin user detected")

 

14. Encoding and Decoding Strings — 

In Python 3, all strings are stored as Unicode, which means they can represent characters from any language — English, Hindi, Chinese, emojis, etc.
However, computers and communication networks don’t understand characters directly — they work with binary data (bytes).

So, to store or transmit text, we must convert strings into bytes — this process is called encoding.
Later, to read or display that data, we convert those bytes back into a string — this process is called decoding.

In short:

  • Encoding → String → Bytes
  • Decoding → Bytes → String

A. Encoding )

Encoding means converting a human-readable string into a machine-readable byte format using a specific character encoding standard such as UTF-8 or ASCII.

When you encode a string, Python uses rules defined by that encoding standard to convert each character into a unique sequence of bytes.
This makes the data ready to be stored in files, sent over networks, or processed by computers.

Example:

s = "Python"
encoded = s.encode('utf-8')
print(encoded)

Output:

b'Python'

Explanation:

  • The prefix b means the data is in byte form.
  • 'utf-8' is the encoding type (UTF-8 supports all major languages and symbols).

Why needed:

  • Computers only understand bytes, not text.
  • Required for file storage, APIs, or communication over the internet.
  • Helps ensure consistent data transfer between systems using different languages or platforms.

B. Decoding 

Decoding is the reverse process of encoding — it converts bytes back into a string using the same encoding format that was used earlier.

Example:

decoded = encoded.decode('utf-8')
print(decoded)

Output:

Python

Explanation:
The .decode() method takes byte data and translates it back into a readable text format. If you use the wrong encoding format while decoding, it may result in errors or incorrect characters.

Practical Uses

✅ Reading or writing text files (like .txt, .csv, .json)
✅ Sending or receiving data over the internet (network communication)
✅ Working with APIs, databases, or web scraping
✅ Handling multilingual text and special symbols correctly

 

15. Docstrings and Multi-line Strings —

A. Multi-line Strings

What It Is:

Multi-line strings are strings that span across multiple lines in Python.
They are created using triple quotes — either ''' ''' or """ """.
Unlike normal single-line strings, multi-line strings automatically preserve line breaks, spacing, and indentation exactly as written.

Example:

message = """This is
a multi-line
string in Python."""
print(message)

Output:

This is
a multi-line
string in Python.

Why It Is Used:

  • To write long text blocks without breaking them into multiple single-line strings.
  • Useful for writing formatted messages, paragraphs, SQL queries, or file content.
  • Makes the code cleaner and more readable when dealing with long text.

B. Docstrings (Documentation Strings)

A docstring is a special type of multi-line string that appears right after a function, class, or module definition.
It is used to describe what the function or class does — serving as internal documentation within your Python code.
Docstrings are enclosed in triple quotes (""" """) and can be accessed at runtime using the __doc__ attribute.

Example:

def greet():
    """This function greets the user."""
    print("Hello!")

print(greet.__doc__)

Output:

This function greets the user.

Why It Is Used:

  • ✅ To explain the purpose and behavior of a function, class, or module.
  • ✅ Helps other developers understand your code easily.
  • ✅ Python tools and IDEs can automatically generate documentation using docstrings.
  • ✅ Improves readability, maintainability, and professionalism of your code.

Example (Class Docstring):

class Student:
    """Represents a student with name and marks."""
    pass

16. String Translation — 

Concept

String translation in Python means replacing or removing multiple characters in a string at once based on a defined mapping.
This process is done using two built-in methods:

  • str.maketrans() — creates the translation table (mapping of characters).
  • translate() — uses that table to actually perform the replacement on the string.

These methods are very useful for text cleaning, data sanitization, simple encryption, and formatting operations.

A. str.maketrans() — Creating the Translation Table

What It Does:

The str.maketrans() method creates a mapping table (a dictionary-like object) that tells Python which characters should be replaced with which.

Syntax:

str.maketrans(from_string, to_string)

Example:

table = str.maketrans('aeiou', '12345')

Explanation:

  • This maps:
    • 'a' → '1'
    • 'e' → '2'
    • 'i' → '3'
    • 'o' → '4'
    • 'u' → '5'
  • The result (table) is a translation table — not a string, but a data structure used by translate().

Advanced Use:
You can also pass a third argument to maketrans() for deleting characters.

table = str.maketrans('', '', 'aeiou')

This means all vowels will be removed when translate() is used.

B. translate() — Applying the Translation

What It Does:

The translate() method takes a translation table (created by maketrans()) and applies it to a string, replacing or deleting characters as per the mapping.

Example:

s = "hello world"
print(s.translate(table))

Output:

h2ll4 w4rld

Explanation:
Each vowel is replaced by its corresponding number according to the mapping table created earlier.

C. Practical Uses

Censoring or cleaning text — remove unwanted words or symbols.
Encoding or simple encryption — substitute letters with numbers or symbols.
Data normalization — replace accented or foreign characters.
Removing characters — for example, strip punctuation or vowels.

Example (Deleting vowels):

table = str.maketrans('', '', 'aeiou')
print("beautiful".translate(table))

Output:

btfl

D. Difference Between str.maketrans() and translate()

Featurestr.maketrans()translate()
PurposeCreates a translation table (mapping of characters).Applies the translation table to a string.
Return TypeReturns a mapping object (dictionary-like).Returns a new string after replacements.
UsageUsed once to define how characters should be replaced or deleted.Used to actually modify the string using that mapping.
Exampletable = str.maketrans('aeiou', '12345')"hello".translate(table) → "h2ll4"
Deletes characters?Yes, by passing the 3rd argument (characters to remove).Performs deletion if the mapping defines it.

 

17. Strings and Memory (Interning)

Concept

String interning is a memory optimization technique in Python where identical immutable strings are stored only once in memory.
If two variables contain the same immutable string, they may share the same memory address to save space and speed up comparisons.

Example 1: Interned Strings

a = "hello"
b = "hello"
print(a is b)

Output:

True

Explanation:

  • Both a and b refer to the same memory location.
  • Python automatically interns short and common strings.

Example 2: Dynamically Created Strings

a = "Py" + "thon"
b = "Python"
print(a is b)

Output:

True

But sometimes:

a = "".join(["Py", "thon"])
b = "Python"
print(a is b)

Output:

False

Explanation:

  • Strings created at runtime may not always be interned automatically.
  • You can use the sys.intern() function to explicitly intern strings.

Why Interning Matters

  • Improves memory efficiency (especially with many identical strings).
  • Speeds up string comparisons since identical interned strings are compared by reference instead of content.
  • Commonly used in compilers, interpreters, and symbol tables.

Example with sys.intern()

import sys
a = sys.intern("example")
b = sys.intern("example")
print(a is b)

Output:

True

18. Example: Putting It All Together

text = "   Python Is Fun!   "

# Step 1: Clean the text
clean = text.strip()

# Step 2: Change case
lowercase = clean.lower()

# Step 3: Replace a word
replaced = lowercase.replace("python", "coding")

# Step 4: Reverse it
reversed_text = replaced[::-1]

print("Original:", text)
print("Modified:", replaced)
print("Reversed:", reversed_text)

Output:

Original:    Python Is Fun!   
Modified: coding is fun!
Reversed: !nuf si gnidoc

 Summary 

ConceptDescription
Indexing & SlicingExtracting characters and substrings
String MethodsModifying and cleaning text
Searching & ReplacingFinding and editing words
ValidationUsing isalpha(), isdigit(), etc.
Palindrome & Anagram LogicApplying algorithmic thinking
f-Strings & FormattingEmbedding variables dynamically
String LoopsIterating and analyzing data

 

Next Blog- Strings in Python (Practice Problems with Solutions)

Sanjiv
0

You must logged in to post comments.

Get In Touch

G06, Kristal Olivine Bellandur near Bangalore Central Mall, Bangalore Karnataka, 560103

+91-8076082435

techiefreak87@gmail.com