#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
•Question 4 of 41easy

Strings in Python

Working with strings in Python.

What You'll Learn

  • How strings work in Python
  • String creation and manipulation
  • All major string methods
  • String formatting techniques (f-strings, format, %)
  • Common string operations for interviews

Understanding Python Strings

In Python, strings are immutable sequences of Unicode characters. This means once a string is created, it cannot be modified in place. Any operation that appears to modify a string actually creates a new string object.

Strings are one of the most commonly used data types, essential for text processing, file handling, and data manipulation.

Creating Strings

code.pyPython
# Single or double quotes - no difference
single = 'Hello'
double = "World"

# Triple quotes for multiline strings
multiline = """This is
a multiline
string"""

# Raw strings (ignores escape sequences)
raw = r"C:\Users\name"  # Backslashes are literal
print(raw)  # C:\Users\name

# Unicode strings
emoji = "Python is fun! šŸ"

# Empty string
empty = ""

String Indexing and Slicing

code.pyPython
s = "Python"
#    012345  (positive indices)
#   -6-5-4-3-2-1  (negative indices)

# Indexing (single character)
print(s[0])    # 'P' (first character)
print(s[-1])   # 'n' (last character)
print(s[2])    # 't'

# Slicing [start:end:step]
print(s[0:3])   # 'Pyt' (indices 0,1,2)
print(s[2:])    # 'thon' (from index 2 to end)
print(s[:4])    # 'Pyth' (from start to index 3)
print(s[::2])   # 'Pto' (every 2nd character)
print(s[::-1])  # 'nohtyP' (reverse string)

# Strings are immutable
# s[0] = 'J'  # TypeError: strings are immutable

String Methods

Case Methods

code.pyPython
text = "hello World"

text.upper()       # "HELLO WORLD"
text.lower()       # "hello world"
text.capitalize()  # "Hello world"
text.title()       # "Hello World"
text.swapcase()    # "HELLO wORLD"

Search Methods

code.pyPython
text = "Hello World"

text.find("World")     # 6 (index of first occurrence)
text.find("Python")    # -1 (not found)
text.index("World")    # 6 (raises ValueError if not found)
text.count("l")        # 3
text.startswith("He")  # True
text.endswith("ld")    # True
"World" in text        # True

Modification Methods

code.pyPython
text = "  Hello World  "

text.strip()           # "Hello World" (remove both sides)
text.lstrip()          # "Hello World  " (remove left)
text.rstrip()          # "  Hello World" (remove right)
text.replace("World", "Python")  # "  Hello Python  "

# Split and join
"a,b,c".split(",")     # ["a", "b", "c"]
",".join(["a", "b"])   # "a,b"

# Padding
"42".zfill(5)          # "00042"
"Hi".ljust(10)         # "Hi        "
"Hi".rjust(10)         # "        Hi"
"Hi".center(10)        # "    Hi    "

Validation Methods

code.pyPython
"hello".isalpha()      # True (all letters)
"12345".isdigit()      # True (all digits)
"hello123".isalnum()   # True (letters or digits)
"   ".isspace()        # True (all whitespace)
"Hello".isupper()      # False
"hello".islower()      # True

String Formatting

F-Strings (Python 3.6+) - Recommended

code.pyPython
name = "Alice"
age = 25
price = 19.99

# Basic
print(f"Name: {name}, Age: {age}")

# Expressions
print(f"Next year: {age + 1}")
print(f"Uppercase: {name.upper()}")

# Formatting numbers
print(f"Price: USD {price:.2f}")    # USD 19.99
print(f"Percent: {0.75:.1%}")     # 75.0%
print(f"Padded: {42:05d}")        # 00042

# Alignment
print(f"{'left':<10}")    # "left      "
print(f"{'right':>10}")   # "     right"
print(f"{'center':^10}")  # "  center  "

.format() Method

code.pyPython
# Positional
"{} is {} years old".format("Alice", 25)

# Named
"{name} is {age} years old".format(name="Alice", age=25)

# Numbered
"{0} and {1}".format("spam", "eggs")

% Formatting (Legacy)

code.pyPython
"Name: %s, Age: %d" % ("Alice", 25)
"Price: %.2f" % 19.99

Common String Operations

code.pyPython
# Concatenation
s = "Hello" + " " + "World"

# Repetition
s = "Ha" * 3  # "HaHaHa"

# Length
len("Python")  # 6

# Membership
"Py" in "Python"  # True

# Iteration
for char in "Python":
    print(char)

# Convert to list of characters
list("abc")  # ['a', 'b', 'c']

Escape Sequences

EscapeMeaning
\nNewline
\tTab
\\Backslash
\'Single quote
\"Double quote
code.pyPython
print("Line 1\nLine 2")
print("Tab\there")
print("He said \"Hi\"")

Interview Tip

When asked about Python strings:

  1. Emphasize strings are immutable sequences
  2. Know indexing and slicing syntax [start:end:step]
  3. Be familiar with common methods (split, join, strip, find)
  4. F-strings are the modern, preferred formatting approach
  5. Explain that string operations return new strings