LearnFrenzy
Sign in Take a free test

Python Programming · Topic 6 of 25

Strings Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Strings · Study material

Text is everywhere – names, emails, passwords, file contents, web pages – and in Python all of it is a str: an immutable sequence of Unicode characters. Strings are the single most tested topic in Python written rounds: slicing with negative steps, what find() returns when nothing is found, why s.upper() "does nothing", and how split() differs from split(" "). This topic covers literals, indexing, slicing, immutability, the essential methods and formatting, then 50 practice questions run on Python 3.

On this page

  • String literals: quotes, triple quotes, escapes and raw strings
  • Indexing and slicing (including negative steps)
  • Immutability, + and *
  • Essential methods: case, strip, split, join, find, count, replace
  • Character tests, ord() and chr()
  • f-strings and format specifications

Creating strings

Single and double quotes are equivalent – pick the one that avoids escaping. Triple quotes ("""…""") span lines. Escape sequences start with a backslash: \n newline, \t tab, \\ backslash, \' quote. A raw string (r"…") keeps backslashes literally – ideal for Windows paths and regular expressions.

single = 'It\'s here'               # escape the quote …
double = "It's here"                # … or use the other kind of quote
multi = """Line one
Line two"""                         # triple quotes keep newlines
path = r"C:\new\table"              # raw string: backslashes stay as they are

print(single == double)
print(multi)
print(path, len(path))
print("Tab:\t|", "Newline count:", "a\nb\nc".count("\n"))

Output

True
Line one
Line two
C:\new\table 12
Tab:	| Newline count: 2

Indexing and slicing

Characters are numbered from 0; negative indexes count from the end (-1 is the last). s[i] outside the string raises IndexError, but a slice s[start:stop:step] never does – it just returns fewer characters. stop is excluded, omitted parts default to the ends, and a negative step walks backwards, so s[::-1] reverses a string.

s = "LEARNFRENZY"
#    0123456789A    (positive indexes)
print(s[0], s[4], s[-1], s[-3])      # first, fifth, last, third from the end
print(s[0:5], s[5:], s[:5])          # stop is excluded
print(s[::2], s[::-1])               # every 2nd character; reversed
print(s[-6:-1], s[100:], len(s))     # slices never raise IndexError

Output

L N Y N
LEARN FRENZY LEARN
LANRNY YZNERFNRAEL
FRENZ  11

Strings are immutable

You cannot change a character in place – s[0] = "J" is a TypeError. Every method that seems to modify a string (upper, replace, strip …) returns a new string; if you do not assign the result, it is lost. + joins strings and * repeats them.

name = "python"
upper = name.upper()        # methods RETURN a new string …
print(name, upper)          # … the original is unchanged

name = name.capitalize()    # to "change" a string, rebind the name
print(name)

fixed = "J" + "ava"[1:]     # build a new string from pieces
print(fixed, "na" * 3, "-" * 10)

Output

python PYTHON
Python
Jva nanana ----------

Essential string methods

MethodWhat it does
lower(), upper(), title(), capitalize(), swapcase()change case
strip(), lstrip(), rstrip()remove whitespace (or given characters) from the ends
split(sep), splitlines()break into a list; with no argument, split on runs of whitespace
sep.join(iterable)join strings with sep between them
find() / rfind()first / last position, or -1 if absent
index()like find, but raises ValueError if absent
count(sub)non-overlapping occurrences
replace(old, new, count)replace all (or the first count) occurrences
startswith(), endswith()prefix / suffix test (accept a tuple)
text = "  Python is fun, Python is popular  "
clean = text.strip()                       # remove surrounding whitespace
print(repr(clean))
print(clean.lower(), "|", clean.title())
print(clean.count("Python"), clean.find("is"), clean.rfind("is"), clean.find("Java"))
print(clean.replace("Python", "Py", 1))
print(clean.startswith("Py"), clean.endswith("ar"))
words = clean.split()                      # split on any whitespace
print(words[:3], len(words))
print("-".join(["2026", "11", "30"]))

Output

'Python is fun, Python is popular'
python is fun, python is popular | Python Is Fun, Python Is Popular
2 7 22 -1
Py is fun, Python is popular
True True
['Python', 'is', 'fun,'] 6
2026-11-30

Character tests, ord() and chr()

isdigit(), isalpha(), isalnum(), isspace(), isupper() and islower() return True only if the string is non-empty and every character passes – so "12.5".isdigit() and "-5".isdigit() are False. ord() gives a character's Unicode code point and chr() goes back.

for s in ["2026", "12.5", "Delhi", "Delhi42", "   ", "hello world"]:
    print(f"{s!r:<14} digit={s.isdigit()!s:<5} alpha={s.isalpha()!s:<5} alnum={s.isalnum()!s:<5} space={s.isspace()}")

print(ord("A"), ord("a"), chr(66), chr(ord("a") + 2))   # code points

Output

'2026'         digit=True  alpha=False alnum=True  space=False
'12.5'         digit=False alpha=False alnum=False space=False
'Delhi'        digit=False alpha=True  alnum=True  space=False
'Delhi42'      digit=False alpha=False alnum=True  space=False
'   '          digit=False alpha=False alnum=False space=True
'hello world'  digit=False alpha=False alnum=False space=False
65 97 B c

Formatting strings

f-strings are the modern way to build text: f"{expr:spec}". The spec controls width and alignment (< > ^), decimals (.2f), thousands separators (,), zero padding (05d), bases (x, b) and percentages (%). str.format() uses the same specs.

name, marks, total = "Asha", 456, 500
pct = marks / total * 100

print(f"{name} scored {marks}/{total} = {pct:.1f}%")
print(f"|{name:<8}|{name:>8}|{name:^8}|")      # align left, right, centre
print(f"{1234567.891:,.2f} {42:05d} {255:x} {0.25:.0%}")
print("{} has {} marks".format(name, marks))   # str.format, still common
print(f"{name=}, {marks=}")                    # = shows the expression too (3.8+)

Output

Asha scored 456/500 = 91.2%
|Asha    |    Asha|  Asha  |
1,234,567.89 00042 ff 25%
Asha has 456 marks
name='Asha', marks=456

Common mistakes

  • Calling a method without assigning – s.strip() alone changes nothing.
  • if s.find(x): – a match at index 0 is falsy and "not found" (-1) is truthy; use x in s.
  • split(" ") on text with several spaces – gives empty strings; use split().
  • ",".join([1, 2]) – join needs strings: ",".join(map(str, nums)).
  • Case-sensitive comparisons – normalise with lower() or casefold().
  • Building long strings with += in a loop – collect pieces and join once.

Key points to remember

  • Strings are immutable sequences of Unicode characters.
  • Indexing out of range is an error; slicing out of range is not.
  • s[::-1] reverses; stop is always excluded.
  • Methods return new strings – assign the result.
  • find returns -1, index raises ValueError.
  • split() with no argument splits on any run of whitespace.
  • String comparison uses code points: "Z" < "a".

Frequently asked questions

Does Python have a char type?

No. A single character is a str of length 1, and s[0] returns one.

How do I reverse a string?

s[::-1], or "".join(reversed(s)).

What is the difference between lower() and casefold()?

casefold() is a stronger, Unicode-aware lowering for caseless comparisons (German "ß" becomes "ss"). For English text they behave the same.

Where can I learn more?

Read Python Strings and Python String Methods in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links