8.1–8.3 Creating and displaying strings
1. What is a string in Python? How can strings be created?
A string is a sequence of characters enclosed in single quotes (' '), double quotes (" ") or triple quotes (''' ''' or """ """). It can contain letters, digits, special characters and spaces.
a = 'Hello World'
b = "Python123!"
c = '''This is a multiline string
with three single quotes'''
d = """This is a multiline string
with three double quotes"""2. Why are different types of quotes provided?
Single quotes make it easy to embed double quotes inside a string, and double quotes make it easy to embed single quotes. Triple quotes allow multiline strings and preserve line breaks (also used for docstrings).
print('He said "Hello"')
print("It's a nice day")3. Does Python have a character data type?
No. A character is treated as a string of length one.
4. What is an index? What are the rules for an index?
An index (subscript) is the positional value of a character in a string. It must always be an integer (positive or negative) and starts from 0.
5. Write the index of each character of msg = "Welcome to Python".
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| msg | W | e | l | c | o | m | e | t | o | P | y | t | h | o | n |
The white spaces at index 7 and 10 are also counted as characters. The length is 17.
6. What does it mean that strings are immutable?
Once created, the contents of a string cannot be changed directly. Any operation that appears to modify a string actually creates a new string object in memory.
s = "Python"
s[0] = "J" # TypeError: 'str' object does not support item assignment
s = "J" + s[1:] # creates a new string "Jython"7. How is the input() function used to read a string?
Syntax: var = input(prompt). It pauses the program until the user types data and presses Enter, then stores it in var as a string. The prompt is optional and is displayed before the input.
name = input("Enter your name: ")
print("Hello,", name)8. What are f-strings? How are they written?
f-strings give a simple and readable way to format strings and embed variables and expressions. The letter f or F is placed immediately before the opening quote, and the variables or expressions are placed inside curly braces { }. Python evaluates them at run time and converts them to strings.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")Output: My name is Alice and I am 30 years old.
9. How can expressions and formatting be used inside an f-string? What does .2f do?
price = 19.99
tax_rate = 0.08
print(price * (1 + tax_rate)) # 21.589199999999998
print(f"Total price: {price * (1 + tax_rate):.2f}") # Total price: 21.59The expression inside the braces is evaluated first. :.2f formats the float with two decimal places (21.59) instead of the long unformatted value.
8.4 Accessing characters and indexing
10. Explain positive and negative indexing with text = "Hello World!".
Positive indices count from the left starting at 0; negative indices count from the right, with –1 for the last character. The first character is at index 0 or –n, where n is the length.
| Positive | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| text | H | e | l | l | o | W | o | r | l | d | ! | |
| Negative | –12 | –11 | –10 | –9 | –8 | –7 | –6 | –5 | –4 | –3 | –2 | –1 |
text[0] and text[-12] give 'H'; text[11] and text[-1] give '!'.
11. For name = "Python", find name[0], name[2], name[-1], name[-6]. What happens for name[6]?
name[0] → 'P'; name[2] → 't'; name[-1] → 'n'; name[-6] → 'P'. name[6] raises an IndexError (string index out of range), since valid indices are 0 to 5.
8.5 String slicing
12. What is slicing? Explain the syntax and the parameters.
Slicing extracts a portion (substring) of a string. Syntax: string_name[start:end:step].
- start: index where slicing begins; inclusive; defaults to 0 if omitted.
- end: index where slicing stops; exclusive; defaults to the end of the string if omitted.
- step: interval between characters; optional, default 1. A negative step slices in reverse order.
Start and end can be positive or negative.
13. For str = "Computer Science", write the index and negative index of each character.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Char | C | o | m | p | u | t | e | r | S | c | i | e | n | c | e | |
| Negative | –16 | –15 | –14 | –13 | –12 | –11 | –10 | –9 | –8 | –7 | –6 | –5 | –4 | –3 | –2 | –1 |
14. Give the output of slicing with positive indices on text = "Computer Science": text[0:8], text[9:], text[:8], text[:].
| Slice | Output | Reason |
|---|---|---|
text[0:8] | Computer | Indices 0 to 7; index 8 (space) is excluded |
text[9:] | Science | From index 9 to the end |
text[:8] | Computer | Start omitted, so begins at 0; same as text[0:8] |
text[:] | Computer Science | Both omitted: the whole string |
15. Give the output of slicing with negative indices: text[-7:-1] and text[-7:].
text[-7:-1] → Scienc. Slicing starts seven characters from the end (at 'S') and stops before index –1, so the last character is excluded.
text[-7:] → Science. With the end omitted, characters up to the end are included.
16. Explain the step parameter with text[0:15:2] and text[7:0:-1].
text[0:15:2] starts at index 0 and takes every second character: indices 0, 2, 4, 6, 8, 10, 12, 14 → Cmue cec.
text[7:0:-1] starts at index 7 ('r') and moves backward; the end index 0 is excluded, so it takes indices 7 to 1 → retupmo.
A step of 1 skips no characters; a step of 2 skips one; a negative step reverses direction.
17. What does s[::-1] do?
With start and end omitted and a step of –1, it returns the whole string in reverse order. For example "Hello"[::-1] gives 'olleH'.
18. Write the output: string = "Python programming"
print(string[7:]) print(string[-11:-1]) print(string[-11:-1:2]) print(string[:6]) print(string[::-1])
The string has 18 characters: P(0) y(1) t(2) h(3) o(4) n(5) space(6) p(7) r(8) o(9) g(10) r(11) a(12) m(13) m(14) i(15) n(16) g(17).
| Statement | Output | Reason |
|---|---|---|
string[7:] | programming | From index 7 to the end |
string[-11:-1] | programmin | –11 is index 7; –1 (the last 'g') is excluded |
string[-11:-1:2] | pormi | Indices 7, 9, 11, 13, 15 |
string[:6] | Python | Indices 0 to 5 |
string[::-1] | gnimmargorp nohtyP | Whole string reversed |
8.6–8.7 Traversal and operations
19. What is string traversal? How is it done?
Traversal is accessing each character of a string one by one, from the first to the last. It is useful for searching, counting occurrences or modifying characters. The most common way is a for loop; index values can also be used.
A = "Hello"
for i in A:
print(i)
for k in range(len(A)): # traversal using index
print(A[k])The first loop prints H, e, l, l, o on separate lines: each character is assigned to i in turn.
20. List the operators that can be used on strings.
| Operation | Operator | Process |
|---|---|---|
| Concatenation | + | Joins two strings |
| Repetition | * | Repeats the string multiple times |
| Membership | in, not in | Checks presence of a substring |
Relational operators > < >= <= == != also compare strings.
21. How are strings compared using relational operators? Evaluate the examples.
Comparison is alphabetical, based on the Unicode values of characters, and is case sensitive. The result is True or False.
| Expression | Result |
|---|---|
"apple" == "apple" | True |
"apple" != "Apple" | True |
"apple" < "banana" | True |
"apple" > "banana" | False |
"a" <= "A" | False (Unicode of 'a' is 97, 'A' is 65) |
"curd" >= "milk" | False |
22. Explain concatenation with an example.
The + operator joins strings and generates a new string.
s1 = "Guido"
s2 = " van Rossum"
s3 = " is known as the father of Python programming Language"
print(s1 + s2 + s3)Output: Guido van Rossum is known as the father of Python programming Language
23. Explain repetition with an example.
The * operator repeats a string a specified number of times.
print("India " * 3)Output: India India India
24. Explain the membership operators with examples.
in returns True if a substring is present in the string; not in returns True if it is absent.
print("He" in "Hello") # True
print("lo" not in "Hello") # False
print("hi" in "Hello") # False8.7 Built-in string functions
25. Explain the built-in string functions with examples.
| Function | Description | Example | Output |
|---|---|---|---|
capitalize() | First character to uppercase | "hello".capitalize() | 'Hello' |
count() | Counts occurrences of a substring | "banana".count("a") | 3 |
find() | First index of substring; –1 if not found | "apple".find("p") | 1 |
index() | Index of substring; error if not found | "pineapple".index("e") | 4 |
len() | Number of characters | len("Hello World") | 11 |
replace() | Replaces a substring with another | 'hello world'.replace('world','Python') | 'hello Python' |
startswith() | True if string starts with the substring | "hello".startswith("he") | True |
endswith() | True if string ends with the substring | "hello".endswith("hi") | False |
These functions return a new string or a Boolean value; the original string is not changed.
26. Differentiate between find() and index().
Both return the index of the first occurrence of a substring. If the substring is absent, find() returns –1, whereas index() raises a ValueError. For example "apple".find("z") is –1, but "apple".index("z") gives an error.
27. Predict the output: (a) "mississippi".count("ss") (b) "Python".find("on") (c) "abc".replace("b","XY") (d) "banana".capitalize()
(a) 2 (b) 4 (c) 'aXYc' (d) 'Banana'
8.8 Applications of strings
28. Write a user-defined function to reverse a string using slicing (Problem 8.1).
def reversed_string(s):
reversed_s = s[::-1]
print(f"Original string: {s}")
print(f"Reversed string: {reversed_s}")
reversed_string("Hello, Python!")Output:Original string: Hello, Python!Reversed string: !nohtyP ,olleH
29. Write a program to check whether a string is a palindrome.
A palindrome reads the same forwards and backwards.
def is_palindrome(s):
return s == s[::-1]
word = input("Enter a string: ")
if is_palindrome(word):
print("Palindrome")
else:
print("Not Palindrome")
| Input | Output |
|---|---|
| 'madam' | Palindrome |
| 'python' | Not Palindrome |
| 'noon' | Palindrome |
30. Write a function to count the vowels in a string (Problem 8.2). Test with "Say Yes to Life, No to drugs".
def count_vowels(sentence):
vowels = "aeiouAEIOU"
count = 0
for ch in sentence:
if ch in vowels:
count = count + 1
print("Sentence:", sentence)
print("Number of vowels:", count)
count_vowels("Say Yes to Life, No to drugs")The vowels, in order, are a (Say), e (Yes), o (to), i and e (Life), o (No), o (to) and u (drugs): the total is 8.
31. Write a function to count the digits in a string.
def count_digits(s):
digits = "0123456789"
count = 0
for ch in s:
if ch in digits:
count = count + 1
return count
print(count_digits('C2b')) # 1
print(count_digits('April 23, 1984')) # 632. Write a function that replaces placeholders USER and COUNT in a template (Problem 8.3).
def format_message(name, item_count):
message_template = "Hello USER! You have COUNT items in your cart"
replaced_name = message_template.replace("USER", name)
final_message = replaced_name.replace("COUNT", str(item_count))
print(f"Original template: {message_template}")
print(f"Formatted message: {final_message}")
format_message("Aysha", 3)Output includes Hello Aysha! You have 3 items in your cart. str() is needed because replace() works with strings, not integers.
33. Print the length of a string without using built-in functions (Problem 8.4).
text = input("Enter a string: ")
count = 0
for ch in text:
count = count + 1
print("Number of characters:", count)The loop runs once for each character, and count increases by 1 each time. For "Python" the output is 6.
34. Write a function that returns how many times the second string occurs in the first.
def occurrences(s1, s2):
return s1.count(s2)
print(occurrences("she sells seashells by the seashore", "sh")) # 3
print(occurrences("it is what it is", "is")) # 2Without count(), using slicing:
def occurrences(s1, s2):
n = len(s2)
total = 0
for i in range(len(s1) - n + 1):
if s1[i:i+n] == s2:
total = total + 1
return total35. Write a function for the Caesar cipher that shifts each letter by a given value.
def caesar(text, shift):
result = ""
for ch in text:
if ch.isupper():
result += chr((ord(ch) - 65 + shift) % 26 + 65)
elif ch.islower():
result += chr((ord(ch) - 97 + shift) % 26 + 97)
else:
result += ch # spaces and symbols unchanged
return result
print(caesar("ATTACK AT DAWN", 3)) # DWWDFN DW GDZQ
print(caesar("CALL ME TOMORROW", 3)) # FDOO PH WRPRUURZord() gives the character's numeric code and chr() converts a code back to a character. The remainder % 26 wraps the letter from Z back to A. These two functions are not discussed in the chapter itself.
36. Short answer / fill in the blanks.
- Strings are enclosed in ______, ______ or ______ quotes: single, double, triple.
- A string cannot be changed after creation, so it is ______: immutable.
- Index of the last character of a string of length n: n – 1 (or –1).
- In
s[a:b], the character at index b is ______: excluded. - Prefix letter that identifies an f-string: f (or F).
- Function that returns –1 when a substring is absent: find().
- Error for accessing an index beyond the string length: IndexError.