Placement Prep

String Operations in Python: 10 Programs Every Fresher Should Know

Master Python string operations with 10 working code examples: reverse, concatenate, check palindromes, count vowels, and format strings. Built for placement prep.

By FACE Prep Team 4 min read
python string-operations placement-prep coding-rounds python-programs

Python treats strings as immutable sequences, and the six core operations below cover most of what placement coding rounds test.

For broader practice beyond strings, the Python basic programs collection has runnable examples across loops, lists, and arithmetic that pair well with the programs here.

Core String Operations in Python

Six operations form the working foundation of all string handling: printing, measuring length, assigning, reversing, concatenating, and comparing. Each one below has a code block you can run directly.

The simplest operation. print() writes the string value to standard output:

str1 = "Focus"
print(str1)
# Output: Focus

Find the Length

len() returns the number of characters, including spaces and punctuation:

str1 = "Focus"
print(len(str1))
# Output: 5

Assign (Copy) a String

Python string assignment creates another name pointing to the same immutable object. Because strings cannot be changed in place, both names behave identically as a copy:

str1 = "Focus"
str2 = str1
print(str2)
# Output: Focus

Reverse a String

Slice notation [::-1] reads a sequence from end to start by setting the step to -1. This pattern is documented in the Python 3 sequence types reference:

str1 = "Focus"
reversed_str = str1[::-1]
print(reversed_str)
# Output: sucoF

No loop required. The same pattern reverses lists and tuples too.

Concatenate Two Strings

The + operator joins two strings into a new one. For joining many strings in a loop, "".join(list_of_strings) is faster:

str1 = "Focus"
str2 = "Academy"
result = str1 + str2
print(result)
# Output: FocusAcademy

Compare Two Strings

The == operator compares content. The is operator compares identity (whether both names point to the same object in memory), which is a common interview trap:

str1 = "Focus"
str2 = "Academy"
print(str1 == str2)    # Output: False
print(str1 == "Focus") # Output: True

Always use == for string comparison in placement-test code. Using is gives unreliable results for strings created at runtime.


Built-in String Methods for Placement Tests

The Python 3 string methods reference lists over 40 methods. The ten below appear most often in coding tests:

MethodWhat it returnsExample output
upper()Uppercase copy"focus".upper()"FOCUS"
lower()Lowercase copy"FOCUS".lower()"focus"
strip()Copy with leading/trailing whitespace removed" hi ".strip()"hi"
split()List split on whitespace by default"a b c".split()["a","b","c"]
join()Joins iterable with separator"-".join(["a","b","c"])"a-b-c"
replace()Replaces all occurrences of a substring"aaa".replace("a","b")"bbb"
count()Count of non-overlapping matches"banana".count("a")3
find()Index of first match, -1 if absent"focus".find("c")2
startswith()Boolean prefix check"focus".startswith("f")True
endswith()Boolean suffix check"focus".endswith("s")True

When tests feed raw input() lines, strip() removes accidental whitespace and split() breaks the line into tokens. These two calls appear at the top of almost every solution that handles space-separated input.


String Programs for Placement Coding Rounds

The four programs below cover most of the string questions in aptitude tests and company coding rounds. Each handles input() directly and is runnable as-is.

Palindrome Check

A string is a palindrome when s == s[::-1]. One slice makes this a single comparison:

str1 = input("Enter string: ").strip()
is_palindrome = str1 == str1[::-1]
print("Palindrome" if is_palindrome else "Not a palindrome")
  • For “radar”: "radar"[::-1] gives "radar". Match → Palindrome.
  • For case-insensitive checks, normalise first: str1.lower() == str1.lower()[::-1].

The palindrome check uses the same per-character logic covered in checking whether a character is upper case, lower case, number, or special character.

Count Vowels

str1 = input("Enter string: ").strip()
count = sum(1 for char in str1 if char.lower() in "aeiou")
print(f"Vowel count: {count}")
  • For “Focus”: o is a vowel, u is a vowel. Count = 2.
  • char.lower() handles uppercase input without adding a separate branch.

Remove Vowels

str1 = input("Enter string: ").strip()
result = "".join(char for char in str1 if char.lower() not in "aeiou")
print(result)
  • For “Focus”: keeps F, c, s. Output: Fcs.

Toggle Case

str.swapcase() handles alternating case in one call. When interviewers ask for the manual version (which they sometimes do, to test loop logic):

str1 = input("Enter string: ").strip()
toggled = "".join(
    char.upper() if i % 2 == 0 else char.lower()
    for i, char in enumerate(str1)
)
print(toggled)
  • For “Focus”: F(index 0, even)→F, o(index 1, odd)→o, c(index 2, even)→C, u(index 3, odd)→u, s(index 4, even)→S. Output: FoCuS.

For sorting a string alphabetically (a related variation that appears in similar test questions), see sorting a string in alphabetical order in Python.


String Formatting in Python

Three formatting styles appear in placement questions and production code:

StyleSyntaxAvailable since
% operator"Hello, %s" % namePython 2 and 3
str.format()"Hello, {}".format(name)Python 2.6+
f-stringsf"Hello, {name}"Python 3.6+

f-strings are the current standard for new code. They evaluate expressions inline: f"2 + 2 = {2 + 2}" prints 2 + 2 = 4. For placement-test input and output:

name = input("Enter name: ").strip()
age = int(input("Enter age: ").strip())
print(f"Name: {name}, Age: {age}")

The % style still appears in legacy codebases and older test banks, so recognising it is worth the ten-minute read.

The same string-assembly pattern scales directly to LLM applications, where a prompt is a formatted string built from user input and system instructions. TinkerLLM gives you live LLM API access for ₹299, so the f-string formatting patterns from this section translate directly into a working prompt-assembly project you can show on your resume.

Primary sources

Frequently asked questions

How do you reverse a string in Python?

Use slice notation: str[::-1]. This reads the string backward by stepping -1 through its characters. For 'radar', the result is also 'radar' because it is a palindrome.

Are Python strings mutable or immutable?

Immutable. You cannot change individual characters in place. Methods like upper() or replace() return a new string; the original is unchanged.

What does [::-1] do in Python?

It is a slice with start=None, stop=None, step=-1. Python sequence types support slicing as [start:stop:step]; a step of -1 reads the sequence in reverse order.

What is the difference between == and is for string comparison?

== compares the content of two strings. is compares identity, checking whether both variables point to the same object in memory. Always use == in placement test code.

How do you count vowels in a string using Python?

Use a generator expression: sum(1 for char in s if char.lower() in 'aeiou'). This handles both uppercase and lowercase input in one pass.

How do you split a string into individual characters in Python?

Use list(s) or iterate directly with for char in s. For example, list('Focus') returns ['F', 'o', 'c', 'u', 's'].

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