Placement Prep

Python Strings: Indexing, Slicing, and Key Methods

Python strings are immutable sequences of Unicode characters. Learn indexing, slicing, split, join, replace, format(), and f-strings with working code examples.

By FACE Prep Team 5 min read
python strings placement-prep python-methods coding-practice string-formatting

A string in Python is a sequence of Unicode characters, and immutability is its defining trait: every method that appears to modify a string is actually returning a new one.

That distinction matters in placement coding tests. A candidate who tries s[0] = 'P' and gets a TypeError mid-test loses time figuring out why. Understanding what strings are and how Python represents them takes ten minutes; it saves you from that specific failure mode entirely.

What is a Python string?

According to the Python documentation, strings in Python are sequences of Unicode code points. Every character (English letter, digit, space, Tamil letter, emoji) maps to a code point in the Unicode standard. Python uses this by default, which means you don’t need any special library to work with multilingual text.

Three structural facts worth knowing:

  • Strings are stored as arrays of bytes representing Unicode characters.
  • Python has no separate character type. A single character like 'A' is just a string of length 1.
  • Strings support both positive indexing (from the start) and negative indexing (from the end).

The practical consequence: everything in Python that handles text (reading files, parsing input, building output) works with strings. Getting comfortable with string operations is not optional for placement coding rounds.

Creating strings and escape sequences

Python accepts three quoting styles for string literals:

# Single quotes
name = 'FACE Prep'

# Double quotes
city = "Coimbatore"

# Triple quotes -- spans multiple lines
bio = """B.E. CSE, 2026
Tier-2 college, Tamil Nadu"""

Use double quotes when the string contains a single quote, and vice versa. Triple quotes handle multiline content without any escaping.

Escape sequences

When you need special characters inside a string, prefix them with a backslash:

EscapeMeaning
\nNewline
\tHorizontal tab
\'Single quote
\"Double quote
\\Backslash itself
line = 'I\'m preparing for placements'
path = 'C:\\Users\\Student\\resume.pdf'
print(line)  # I'm preparing for placements
print(path)  # C:\Users\Student\resume.pdf

Raw strings

When you want the backslash treated literally (common in file paths and regular expressions), prefix the string with r or R:

raw = r'C:\Users\Student\resume.pdf'
print(raw)  # C:\Users\Student\resume.pdf

Raw strings do not process any escape sequences. Everything after r' is taken as-is.

Indexing, slicing, and immutability

Every character in a string has two indices: a positive one counting from the left (starting at 0), and a negative one counting from the right (starting at -1).

s = "python"
#    0 1 2 3 4 5   <- positive indices
#   -6-5-4-3-2-1   <- negative indices

print(s[0])   # p
print(s[-1])  # n
print(s[2])   # t
print(s[-3])  # h

Slicing

Slicing extracts a portion of a string using s[start:end:step]. The end index is excluded.

s = "placement"

print(s[0:5])   # place  (index 0 to 4)
print(s[5:])    # ment   (index 5 to end)
print(s[:4])    # plac   (start to index 3)
print(s[-4:])   # ment   (last 4 characters)
print(s[::2])   # paeet  (every second character)
print(s[::-1])  # tnemecalp  (reversed)

The step of -1 is the standard one-liner for reversing a string. It appears frequently in placement coding rounds.

Why immutability matters

Strings cannot be changed in place. Attempting to modify a character by index raises a TypeError:

s = "python"
s[0] = 'P'   # TypeError: 'str' object does not support item assignment

To produce a modified string, create a new one:

s = "python"
s = 'P' + s[1:]
print(s)  # Python

This is not a limitation to work around; it is a design choice. Immutability makes strings safe to use as dictionary keys and means Python can optimise memory use across multiple references to the same string.

For related character-level operations, check whether a character is uppercase or lowercase using the string methods covered in the next section.

Essential string methods for placement tests

The Python string methods reference lists over 40 built-in methods. Placement coding tests concentrate on a core set. Here are the eight that appear most often, with verified outputs:

Case and whitespace

s = "  Hello, World  "

print(s.upper())   # "  HELLO, WORLD  "
print(s.lower())   # "  hello, world  "
print(s.strip())   # "Hello, World"    (removes leading/trailing spaces)
print(s.lstrip())  # "Hello, World  "  (leading only)
print(s.rstrip())  # "  Hello, World"  (trailing only)

split() and join()

split() breaks a string into a list. join() is the inverse.

line = "John,CSE,CGPA:8.2"
parts = line.split(',')
print(parts)  # ['John', 'CSE', 'CGPA:8.2']

words = ['campus', 'placement', 'drive']
sentence = ' '.join(words)
print(sentence)  # campus placement drive

split() called without arguments splits on any whitespace sequence and discards empty strings, which is useful when cleaning messy input.

replace()

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

replace() returns a new string with all occurrences of the first argument replaced by the second. The original string is unchanged.

find() and count()

s = "banana"
print(s.find('a'))    # 1  (first occurrence index)
print(s.find('z'))    # -1 (not found)
print(s.count('a'))   # 3  (number of occurrences)

find() returns -1 when the substring is not found, making it safe to use without a try-except block. The in operator ('a' in 'banana') is cleaner when you only need a boolean.

Combining methods

Placement tests often chain methods. A common pattern: clean input, then process.

raw = "  B.E. CSE, 2026  "
cleaned = raw.strip().lower()
print(cleaned)  # b.e. cse, 2026

For sorting strings alphabetically, see how to sort a string in alphabetical order, which builds directly on these indexing and comparison concepts.

String formatting: format() and f-strings

Two formatting approaches appear in placement coding tests: str.format() for Python 3.x broadly, and f-strings for Python 3.6 and later.

str.format()

name = "Priya"
score = 92

# Positional placeholders
msg = "Candidate {} scored {} in the aptitude test.".format(name, score)
print(msg)  # Candidate Priya scored 92 in the aptitude test.

# Named placeholders
template = "Name: {name}, Score: {score}"
print(template.format(name="Arjun", score=88))
# Name: Arjun, Score: 88

# Formatting numbers
pi_approx = "Pi is approximately {:.2f}.".format(3.14159)
print(pi_approx)  # Pi is approximately 3.14.

F-strings (Python 3.6+)

F-strings prefix the string literal with f or F. Any expression inside {...} is evaluated and inserted directly:

name = "Kavya"
cgpa = 8.7
college = "Tier-2 college, Coimbatore"

intro = f"{name} has a CGPA of {cgpa} from {college}."
print(intro)
# Kavya has a CGPA of 8.7 from Tier-2 college, Coimbatore.

# Expressions work inline
width = 120
height = 80
area_msg = f"Area: {width * height} sq px"
print(area_msg)  # Area: 9600 sq px

F-strings evaluate at runtime, are easier to read, and run faster than str.format(). They are the default choice in Python 3.6+ code.

The f"{variable}" pattern appears again when building prompts for language models: a template string with dynamic context injected at runtime. The string formatting you’ve practised here carries over directly. If you want to see that in action, TinkerLLM’s ₹299 starter track builds its first LLM wrapper around exactly that pattern: the split(), join(), and f-string skills from this article are what you’ll use in the opening project.

Putting it together: a placement-style problem

Placement tests include string manipulation warm-ups with this typical format:

  • Input: A comma-separated line of candidate info, e.g., " Rohan Kumar, ECE, 7.9 "
  • Task: Extract the name, branch, and CGPA as separate variables with no extra whitespace.
raw = "  Rohan Kumar, ECE, 7.9  "
parts = raw.strip().split(', ')

name   = parts[0]
branch = parts[1]
cgpa   = float(parts[2])

print(f"Name: {name}")      # Name: Rohan Kumar
print(f"Branch: {branch}")  # Branch: ECE
print(f"CGPA: {cgpa}")      # CGPA: 7.9

This combines strip(), split(), indexing, float() conversion, and f-string output. Each of those pieces appears individually in Python practice programs; work through those examples alongside this guide.

Primary sources

Frequently asked questions

Can you modify a string in Python?

No. Strings are immutable in Python. You cannot change an individual character with s[0] = 'X'. Instead, build a new string: s = 'X' + s[1:].

What is the difference between str.format() and f-strings?

Both insert values into string templates. F-strings evaluate the expression directly in the literal using f-prefix syntax and are faster at runtime. str.format() is more portable when you need to build template strings dynamically at runtime.

How do you check if a substring exists in a string in Python?

Use the 'in' operator: 'python' in 'learn python' returns True. For the position, use str.find() which returns the index or -1 if not found.

What does split() return in Python?

split() returns a list of substrings. 'a,b,c'.split(',') returns ['a', 'b', 'c']. Called without arguments, split() splits on any whitespace and removes empty strings.

How do you reverse a string in Python?

Use slicing with a step of -1: s[::-1]. For 'python', s[::-1] returns 'nohtyp'. This is the standard one-liner for string reversal in placement coding tests.

What does strip() do in Python?

strip() removes leading and trailing whitespace from a string. lstrip() removes only leading whitespace; rstrip() removes only trailing whitespace. All three return a new string.

What is negative indexing in Python strings?

Python allows negative indices to count from the end of a string. s[-1] is the last character, s[-2] is the second-to-last, and so on. This avoids writing s[len(s)-1].

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF