Your language · Python
Strings
Creating, comparing and changing strings, and why strings cannot be changed in place.
Learn: Strings in Python8 minute read
A string (str) is Python's type for text. Test code uses strings all the time: page text, messages, URLs, JSON (a text format for structured data) and file contents. Interviewers ask about them to check that you know strings never change, that you can cut and join text without surprises, and that you compare text the right way in an assertion.
Step 1: strings are immutable
Immutable means a str object can never change. s[0] = "X" raises TypeError (an error Python raises when a value does not support an operation), and every method that seems to change text, such as upper, replace or strip, returns a new string. If you call title.upper() without assigning the result, title stays the same. Even s += "x" creates a new string and moves the name s to it.
This makes strings safe dictionary keys, because their hash (a number made from the text, which a dict uses to find an entry quickly) never changes, and safe to pass around. It also lets CPython (the standard interpreter, the program that runs Python code) reuse one object for some identical strings, which is called interning. Because of interning, a is b (true only when both names point at the very same object) can be true for two equal strings in one case and false in another, so always compare text with ==.
Step 2: indexing and slicing
A string is a sequence of characters (an ordered row of items). An index is the position number of a character, and counting starts at 0. s[0] is the first character and s[-1] the last. A slice s[start:stop:step] includes start and stops before stop; a missing part means "from the beginning" or "to the end". s[::-1] is the reversed string. A single index out of range raises IndexError (the position does not exist), but a slice never does.
s = "Selenium WebDriver"
print(s[0], s[-1], s[0:8], s[9:], s[-6:])
print(s[::-1])
print(len(s), s.find("Web"), s.find("xyz"), "Web" in s)
title = "Login"
title.upper()
print(title)
title = title.upper()
print(title)
try:
title[0] = "l"
except TypeError as e:
print("TypeError:", e)
S r Selenium WebDriver Driver revirDbeW muineleS 18 9 -1 True Login LOGIN TypeError: 'str' object does not support item assignment
Step 3: the methods you will use in tests
strip()removes spaces from both ends;lower()andcasefold()help with case-insensitive checks.startswith,endswithandin(for "contains").findreturns -1 when the text is missing, whileindexraisesValueError(an error for a bad value).split()with no argument splits on any run of spaces and drops empty parts.split(",")splits on each comma and keeps empty fields."sep".join(items)glues strings together, and every item must already be a string.
f-strings are the clearest way to build a message: f"{name} has {count} items". A format spec (a short code that says how to show the value) comes after a colon, so f"{price:.2f}" shows two decimals. f"{value=}" prints the expression and its value, which helps when debugging. Joining a string and a number with + raises TypeError, so use an f-string or str().
Step 4: building long strings
Because strings cannot change, adding pieces with += in a long loop can copy the growing text again and again. Python's answer to Java's StringBuilder (a Java class that builds text efficiently) is to collect the pieces in a list and call join once. io.StringIO is a writable text buffer (a place to add text piece by piece) for the same job.
cells = ["Asha", " QA ", "Pune"]
row = " | ".join(cell.strip() for cell in cells)
print(row)
print("a b c".split(), "a b c".split(" "))
print("2024-05-01".split("-"))
nums = [1, 2, 3]
print("-".join(str(n) for n in nums))
name, total = "Asha", 1299.5
print(f"{name} paid {total:.2f}", f"{total=}")
expected, actual = "Welcome Back", "welcome back "
print(expected.casefold() == actual.strip().casefold())
print(sorted(["banana", "Apple", "cherry"]), sorted(["banana", "Apple", "cherry"], key=str.lower))
Asha | QA | Pune ['a', 'b', 'c'] ['a', 'b', '', 'c'] ['2024', '05', '01'] 1-2-3 Asha paid 1299.50 total=1299.5 True ['Apple', 'banana', 'cherry'] ['Apple', 'banana', 'cherry']
Strings compare by character code, so capital letters come before small ones: "Zebra" < "apple" is True. In a test, decide whether case and outer spaces matter, then clean both sides the same way. Keep the original text in the failure message (the second part after the comma in assert is the message shown when the check fails):
actual = driver.find_element(By.ID, "toast").text
assert actual.strip() == "Order placed", f"Unexpected toast: {actual!r}"
The !r shows the value in quotes, so extra spaces and empty strings are easy to see in the report.
How to answer in an interview
Give the short rule, then a one-line example. For "why are strings immutable?": "A str never changes; methods return a new string. That keeps the hash stable, so strings work as dict keys, and it makes them safe to share." For "how do you reverse a string?": "s[::-1]. If you want it by hand, I loop from the end and collect characters in a list, then join them."
Common mistakes
- Calling
s.strip()ors.replace(...)without assigning the result. - Comparing strings with
is. - Using
split(" ")on text with double spaces and getting empty items. - Passing numbers to
join, which raisesTypeError. - Building a long report with
+=in a loop instead ofjoin.
Recap
A str never changes, so assign the result of every method. Slices exclude the stop index and s[::-1] reverses. find returns -1 and index raises. split() with no argument handles messy spaces. Build long text with join, format with f-strings, and compare text with == after cleaning both sides the same way.
9 questions0/9 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | == versus is on strings | Easy | Asked in: Capgemini, Infosys |
| Not started | Why are strings immutable in Python? | Easy-Medium | Asked in: Capgemini, Infosys |
| Pro+ | Building strings efficiently: join versus += in a loop | Easy-Medium | |
| Pro+ | Calling upper() without using the result | Easy | Asked in: Capgemini, Infosys |
| Pro+ | Slicing, find and index | Easy-Medium | |
| Pro+ | Formatting with f-strings | Easy-Medium | |
| Pro+ | split() versus split(" ") | Easy-Medium | |
| Pro+ | Joining numbers into one string | Easy-Medium | |
| Pro+ | Comparing text without caring about case | Easy |
The first 2 questions of each topic are free. Pro+ opens every question.