Python Strings
Introduction to Python Strings
A string is a sequence of characters. In Python, strings are sequences of Unicode characters.
Strings are used to store text, names, messages, email addresses, sentences, and other textual information.
For example:
name = "Python"
message = "Hello World"
print(name)
print(message)
Output:
Python
Hello World
Python provides several operations and built-in methods to create, access, manipulate, search, and process strings.
In this tutorial, we will cover:
- Creating Strings
- Accessing Strings and Substrings
- String Indexing
- String Slicing
- Editing and Deleting Strings
- Operations on Strings
- Common String Functions
- String Case Conversion Methods
- Count(), Find() and Index()
- Startswith() and Endswith()
- Format() Method
- String Validation Methods
- Split() and Join()
- Replace() and Strip()
- Practical Python String Programs
1. Creating Strings in Python
Python provides different ways to create strings.
A. Single Quotes
We can create a string using single quotes.
s = 'hello'
print(s)
Output:
hello
B. Double Quotes
We can also create strings using double quotes.
s = "hello"
print(s)
Output:
hello
C. Triple Single Quotes
Triple single quotes are commonly used for multiline strings.
s = '''Hello
Welcome to
Python Programming'''
print(s)
Output:
Hello
Welcome to
Python Programming
D. Triple Double Quotes
We can also use triple double quotes to create multiline strings.
s = """Hello
Welcome to
Python Programming"""
print(s)
Output:
Hello
Welcome to
Python Programming
E. Using the str() Function
Python provides the str() function to create or convert a value into a string.
s = str('hello')
print(s)
print(type(s))
Output:
hello
<class 'str'>
F. Using Quotes Inside Strings
If a string contains an apostrophe, we can use double quotes to enclose it.
s = "it's raining outside"
print(s)
Output:
it's raining outside
2. Accessing Characters from a String
Each character in a Python string has an index position.
Python supports two types of indexing:
- Positive Indexing
- Negative Indexing
Consider the following string:
s = 'hello world'
A. Positive Indexing
Positive indexing starts from the left side of the string. The first character has index 0.
| Character | h | e | l | l | o | Space | w | o | r | l | d |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
Example:
s = 'hello world'
print(s[0])
print(s[1])
print(s[6])
Output:
h
e
w
If we try to access an index outside the valid range, Python raises an IndexError.
s = 'hello world'
print(s[41])
Output:
IndexError: string index out of range
B. Negative Indexing
Negative indexing starts from the right side of the string.
The last character has index -1.
| Character | h | e | l | l | o | Space | w | o | r | l | d |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Negative Index | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Example:
s = 'hello world'
print(s[-1])
print(s[-3])
print(s[-5])
Output:
d
r
w
3. String Slicing in Python
String slicing is used to extract a part of a string.
Syntax
string[start:stop:step]
start: Starting index of the substring.stop: Ending index, which is excluded.step: Number of positions to move between characters.
A. Basic Slicing
s = 'hello world'
print(s[0:5])
print(s[6:11])
Output:
hello
world
B. Slicing with Step
s = 'hello world'
print(s[0:11:2])
Output:
hlowrd
The step value 2 selects every second character.
C. Negative Step Slicing
s = 'hello world'
print(s[6:0:-2])
Output:
wol
D. Reverse a String Using Slicing
We can reverse a string using [::-1].
s = 'hello world'
print(s[::-1])
Output:
dlrow olleh
E. Negative Index Slicing
s = 'hello world'
print(s[-1:-6:-1])
Output:
dlrow
4. Editing and Deleting Strings
A. Editing Strings
Python strings are immutable.
Immutable means that once a string is created, its individual characters cannot be changed directly.
Example:
s = 'hello world'
s[0] = 'H'
print(s)
Output:
TypeError: 'str' object does not support item assignment
However, we can create a new string using concatenation.
s = 'hello world'
s = 'H' + s[1:]
print(s)
Output:
Hello world
B. Deleting a String Variable
We can delete an entire string variable using the del statement.
s = 'hello world'
del s
print(s)
Output:
NameError: name 's' is not defined
After deleting the variable, it cannot be accessed.
C. Deleting Individual Characters
We cannot delete individual characters or slices directly from a string because strings are immutable.
s = 'hello world'
del s[-1:-5:2]
Output:
TypeError: 'str' object does not support item deletion
To remove characters, we need to create a new string.
5. Operations on Strings
Python supports several operations on strings:
- Arithmetic Operations
- Relational Operations
- Logical Operations
- Loops on Strings
- Membership Operations
A. Arithmetic Operations on Strings
Python supports two main arithmetic-style operations on strings: concatenation and repetition.
1. String Concatenation (+)
The + operator joins two or more strings.
print('delhi' + ' ' + 'mumbai')
Output:
delhi mumbai
2. String Repetition (*)
The * operator repeats a string a specified number of times.
print('delhi' * 5)
Output:
delhidelhidelhidelhidelhi
Another example:
print("*" * 50)
Output:
**************************************************
B. Relational Operations on Strings
Relational operators compare two strings and return either True or False.
Python compares strings lexicographically, using Unicode code point values.
Common relational operators:
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example 1: Equality
print('delhi' == 'delhi')
print('delhi' != 'delhi')
Output:
True
False
Example 2: Lexicographical Comparison
print('mumbai' > 'pune')
Output:
False
Because the first character m comes before p in Unicode ordering.
Example 3: Uppercase and Lowercase Comparison
print('Pune' > 'pune')
Output:
False
Uppercase and lowercase characters have different Unicode code points. String comparison is case-sensitive.
C. Logical Operations on Strings
Python supports three logical operators:
andornot
For strings, these operators use truth-value testing.
An empty string '' is considered False, while a non-empty string is considered True.
Example 1: and Operator
print('hello' and 'world')
Output:
world
The and operator returns the first falsy operand, or the last operand if all operands are truthy.
Example 2: or Operator
print('hello' or 'world')
Output:
hello
The or operator returns the first truthy operand. If all operands are falsy, it returns the last operand.
Example 3: Empty String with and
print('' and 'world')
Output:
The empty string is falsy, so it is returned.
Example 4: Empty String with or
print('' or 'world')
Output:
world
Example 5: not Operator
print(not 'hello')
Output:
False
A non-empty string is truthy, so not returns False.
D. Loops on Strings
A string is an iterable sequence of characters. We can use a for loop to access each character.
Example 1: Print Each Character
for i in 'hello':
print(i)
Output:
h
e
l
l
o
Example 2: Print a Different Word for Each Character
for i in 'delhi':
print('pune')
Output:
pune
pune
pune
pune
pune
The loop runs five times because the string delhi contains five characters.
E. Membership Operations on Strings
Membership operators check whether a character or substring exists inside a string.
Python provides two membership operators:
innot in
Example 1: in Operator
print('D' in 'delhi')
print('d' in 'delhi')
Output:
False
True
The comparison is case-sensitive.
Example 2: not in Operator
print('python' not in 'hello world')
print('hello' not in 'hello world')
Output:
True
False
6. Common Built-in Functions for Strings
Python provides several built-in functions that can be used with strings.
A. len()
The len() function returns the total number of characters in a string, including spaces.
s = 'hello world'
print(len(s))
Output:
11
B. max()
The max() function returns the character with the highest Unicode code point.
print(max('hello world'))
Output:
w
C. min()
The min() function returns the character with the lowest Unicode code point.
print(min('hello world'))
Output:
The result is a space character because its Unicode code point is lower than those of the letters.
D. sorted()
The sorted() function returns a list containing the sorted characters of a string.
print(sorted('hello world'))
Output:
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
We can also sort characters in descending order.
print(sorted('hello world', reverse=True))
Output:
['w', 'r', 'o', 'o', 'l', 'l', 'l', 'h', 'e', 'd', ' ']
Important: sorted() returns a list, not a string.
7. String Case Conversion Methods
Python provides several methods to change the case of strings.
A. capitalize()
The capitalize() method converts the first character to uppercase and the remaining characters to lowercase.
s = 'hello world'
print(s.capitalize())
print(s)
Output:
Hello world
hello world
The original string remains unchanged because strings are immutable.
B. title()
The title() method converts the first character of each word to uppercase.
s = 'hello world'
print(s.title())
Output:
Hello World
C. upper()
The upper() method converts all characters to uppercase.
s = 'hello world'
print(s.upper())
Output:
HELLO WORLD
D. lower()
The lower() method converts all characters to lowercase.
print('Hello World'.lower())
Output:
hello world
E. swapcase()
The swapcase() method converts uppercase characters into lowercase and lowercase characters into uppercase.
print('HeLlO WorLD'.swapcase())
Output:
hElLo wORld
Summary of Case Conversion Methods
| Method | Purpose | Example |
|---|---|---|
capitalize() | First character uppercase, remaining lowercase | Hello world |
title() | First character of each word uppercase | Hello World |
upper() | All characters uppercase | HELLO WORLD |
lower() | All characters lowercase | hello world |
swapcase() | Changes uppercase to lowercase and vice versa | hELLO |
8. count(), find() and index() Methods
These methods are used to search for characters or substrings.
A. count()
The count() method returns how many times a particular character or substring appears.
Syntax:
string.count(substring)
Example:
s = 'my name is nitish'
print(s.count('i'))
Output:
3
The character i appears three times.
B. find()
The find() method returns the lowest index where the specified substring is found.
If the substring is not found, it returns -1.
Example 1:
s = 'my name is nitish'
print(s.find('nitish'))
Output:
11
Example 2:
print('my name is nitish'.find('x'))
Output:
-1
C. index()
The index() method also returns the index of the first occurrence of a substring.
However, if the substring is not found, it raises a ValueError.
Example 1:
s = 'my name is nitish'
print(s.index('nitish'))
Output:
11
Example 2:
print('my name is nitish'.index('x'))
Output:
ValueError: substring not found
Difference Between find() and index()
| find() | index() |
|---|---|
| Returns the index when found | Returns the index when found |
Returns -1 if not found | Raises ValueError if not found |
| Useful when a missing substring is expected | Useful when the substring is expected to exist |
9. startswith() and endswith() Methods
These methods check whether a string starts or ends with a particular substring.
A. startswith()
Returns True if the string starts with the specified substring.
s = 'my name is nitish'
print(s.startswith('my'))
print(s.startswith('nitish'))
Output:
True
False
B. endswith()
Returns True if the string ends with the specified substring.
s = 'my name is nitish'
print(s.endswith('nitish'))
print(s.endswith('sho'))
Output:
True
False
These methods are useful for checking file extensions, prefixes, and suffixes.
Example:
filename = 'notes.pdf'
if filename.endswith('.pdf'):
print('PDF file')
Output:
PDF file
10. format() Method in Python
The format() method is used to insert values into a string.
It allows us to create dynamic strings.
Syntax
"Your message {}".format(value)
Example 1: Basic Formatting
name = 'Nitish'
gender = 'male'
message = 'Hi my name is {} and I am a {}'.format(name, gender)
print(message)
Output:
Hi my name is Nitish and I am a male
Example 2: Positional Indexing
name = 'Nitish'
gender = 'male'
message = 'Hi my name is {1} and I am a {0}'.format(gender, name)
print(message)
Output:
Hi my name is Nitish and I am a male
Here:
{0}refers to the first argument.{1}refers to the second argument.
11. String Validation Methods
Python provides methods to check the type of characters present in a string.
These methods return Boolean values: True or False.
A. isalnum()
Returns True if all characters are alphanumeric (letters or digits) and the string is not empty.
print('nitish1234'.isalnum())
print('nitish1234%'.isalnum())
Output:
True
False
The second string contains %, which is not alphanumeric.
B. isalpha()
Returns True if all characters are alphabetic and the string is not empty.
print('nitish'.isalpha())
print('nitish123'.isalpha())
Output:
True
False
C. isdigit()
Returns True if all characters are digits and the string is not empty.
print('12345'.isdigit())
print('123abc'.isdigit())
Output:
True
False
D. isidentifier()
Returns True if the string is a valid Python identifier.
print('first_name'.isidentifier())
print('first-name'.isidentifier())
Output:
True
False
A Python identifier is a valid name used for variables, functions, classes, and other objects.
Summary of Validation Methods
| Method | Purpose | Example |
|---|---|---|
isalnum() | Checks letters and digits | 'abc123'.isalnum() |
isalpha() | Checks alphabetic characters | 'hello'.isalpha() |
isdigit() | Checks digit characters | '123'.isdigit() |
isidentifier() | Checks valid Python identifier | 'first_name'.isidentifier() |
12. split() and join() Methods
The split() and join() methods are used to divide strings and combine string elements.
A. split()
The split() method divides a string into a list of substrings.
By default, it splits the string using whitespace.
Example:
s = 'hi my name is nitish'
print(s.split())
Output:
['hi', 'my', 'name', 'is', 'nitish']
We can also specify a separator.
s = 'apple,banana,mango'
print(s.split(','))
Output:
['apple', 'banana', 'mango']
B. join()
The join() method combines elements of an iterable into a single string using a separator.
Example:
words = ['hi', 'my', 'name', 'is', 'nitish']
print(" ".join(words))
Output:
hi my name is nitish
Another example:
words = ['Python', 'Java', 'C++']
print("-".join(words))
Output:
Python-Java-C++
Important: All elements passed to join() must be strings.
13. replace() Method
The replace() method replaces an existing substring with another substring.
Syntax:
string.replace(old, new)
Example 1: Replace a Word
s = 'hi my name is nitish'
print(s.replace('nitish', 'campusx'))
Output:
hi my name is campusx
Example 2: Replace a Character
s = 'banana'
print(s.replace('a', 'o'))
Output:
bonono
The original string remains unchanged unless the returned string is assigned to a variable.
14. strip() Method
The strip() method removes leading and trailing whitespace from a string.
Example 1: Remove Spaces
s = 'nitish '
print(s.strip())
Output:
nitish
Example 2: Remove Leading and Trailing Spaces
s = ' hello world '
print(s.strip())
Output:
hello world
Related Methods
| Method | Purpose |
|---|---|
strip() | Removes leading and trailing whitespace |
lstrip() | Removes leading whitespace |
rstrip() | Removes trailing whitespace |
Example:
s = ' hello '
print(s.lstrip())
print(s.rstrip())
print(s.strip())
Output:
hello
hello
hello
15. Important Python String Methods Summary
| Method | Description |
|---|---|
capitalize() | Capitalizes the first character |
title() | Capitalizes the first character of each word |
upper() | Converts string to uppercase |
lower() | Converts string to lowercase |
swapcase() | Swaps uppercase and lowercase |
count() | Counts occurrences |
find() | Finds substring index; returns -1 if absent |
index() | Finds substring index; raises ValueError if absent |
startswith() | Checks starting substring |
endswith() | Checks ending substring |
format() | Inserts values into a string |
isalnum() | Checks alphanumeric characters |
isalpha() | Checks alphabetic characters |
isdigit() | Checks digit characters |
isidentifier() | Checks valid identifier |
split() | Splits a string into a list |
join() | Joins strings using a separator |
replace() | Replaces a substring |
strip() | Removes leading and trailing whitespace |
16. Practical Python String Programs
The following programming exercises are based on the examples in the uploaded notebook.
Program 1: Find the Length of a String Without Using len()
Problem: Write a Python program to calculate the length of a string without using the built-in len() function.
Program:
s = input('Enter the string: ')
counter = 0
for i in s:
counter += 1
print('Length of string is', counter)
Sample Input:
Enter the string: Python
Output:
Length of string is 6
Explanation:
The loop iterates through every character and increases the counter by one.
Program 2: Extract Username from an Email Address
Problem: Extract the username from an email address.
For example:
nitish24singh@gmail.com
Expected username:
nitish24singh
Program:
s = input('Enter the email: ')
pos = s.index('@')
print(s[0:pos])
Sample Input:
Enter the email: nitish24singh@gmail.com
Output:
nitish24singh
Explanation:
index('@')finds the position of the@symbol.s[0:pos]extracts everything before it.
Program 3: Count the Frequency of a Character
Problem: Count how many times a particular character occurs in a string.
For example:
String: hello how are you
Character: h
Frequency: 2
Program:
s = input('Enter the string: ')
term = input('What would you like to search for? ')
counter = 0
for i in s:
if i == term:
counter += 1
print('Frequency:', counter)
Sample Input:
Enter the string: hello how are you
What would you like to search for? h
Output:
Frequency: 2
Program 4: Remove a Particular Character from a String
Problem: Write a program that removes a specified character from a string.
Program:
s = input('Enter the string: ')
term = input('What would you like to remove? ')
result = ''
for i in s:
if i != term:
result = result + i
print(result)
Sample Input:
Enter the string: banana
What would you like to remove? a
Output:
bnn
Explanation:
The loop checks each character. If it is not equal to the specified character, it is added to the result.
Program 5: Check Whether a String Is Palindrome
Problem: A palindrome is a word or string that reads the same forward and backward.
Examples:
abbamalayalammadam
Program:
s = input('Enter the string: ')
flag = True
for i in range(0, len(s) // 2):
if s[i] != s[len(s) - i - 1]:
flag = False
print('Not a Palindrome')
break
if flag:
print('Palindrome')
Sample Input 1:
Enter the string: malayalam
Output:
Palindrome
Sample Input 2:
Enter the string: python
Output:
Not a Palindrome
Explanation:
The program compares the first character with the last character, the second with the second-last, and so on.
If any pair does not match, the string is not a palindrome.
Program 6: Count Words in a String Without Using split()
Problem: Write a Python program to count the number of words in a string without using the split() method.
Program:
s = input('Enter the string: ')
L = []
temp = ''
for i in s:
if i != ' ':
temp = temp + i
else:
if temp:
L.append(temp)
temp = ''
if temp:
L.append(temp)
print('Words:', L)
print('Number of words:', len(L))
Sample Input:
Enter the string: hi my name is nitish
Output:
Words: ['hi', 'my', 'name', 'is', 'nitish']
Number of words: 5
Explanation:
- The loop reads every character.
- Characters are added to
tempuntil a space is encountered. - When a space is encountered, the completed word is added to the list.
- Finally, the last word is added.
This version also handles multiple consecutive spaces.
Program 7: Convert a String to Title Case Without Using title()
Problem: Convert the first character of every word to uppercase without using the title() method.
Program:
s = input('Enter the string: ')
L = []
for i in s.split():
L.append(i[0].upper() + i[1:].lower())
print(" ".join(L))
Sample Input:
Enter the string: hello my name is nitish
Output:
Hello My Name Is Nitish
Explanation:
split()separates the words.i[0].upper()converts the first character to uppercase.i[1:].lower()converts the remaining characters to lowercase.join()combines all words into a single string.
Program 8: Convert an Integer into a String Without Using str()
Problem: Write a Python program to convert an integer into a string without using the built-in str() function.
Program:
number = int(input('Enter the number: '))
digits = '0123456789'
result = ''
if number == 0:
result = '0'
while number != 0:
result = digits[number % 10] + result
number = number // 10
print(result)
print(type(result))
Sample Input:
Enter the number: 12345
Output:
12345
<class 'str'>
Explanation:
number % 10extracts the last digit.- The
digitsstring maps each integer digit to its character. - The extracted character is added to the beginning of the result.
number // 10removes the last digit.- The process continues until the number becomes zero.
This example handles non-negative integers. Negative numbers require additional sign handling.
17. Practice Questions (MCQs)
Q1. What is a string in Python?
A. A collection of integers only
B. A sequence of Unicode characters
C. A collection of functions
D. A mathematical expression
Correct Answer: B. A sequence of Unicode characters
Q2. Which property describes Python strings?
A. Mutable
B. Immutable
C. Unordered
D. Numeric only
Correct Answer: B. Immutable
Q3. What is the output of the following code?
s = 'hello'
print(s[-1])
A. h
B. e
C. o
D. l
Correct Answer: C. o
Q4. What is the output of the following code?
s = 'hello'
print(s[::-1])
A. hello
B. olleh
C. lleho
D. Error
Correct Answer: B. olleh
Q5. Which operator is used to concatenate two strings?
A. *
B. -
C. +
D. /
Correct Answer: C. +
Q6. What does len('Python') return?
A. 5
B. 6
C. 7
D. 8
Correct Answer: B. 6
Q7. Which method converts a string into uppercase?
A. lower()
B. capitalize()
C. upper()
D. title()
Correct Answer: C. upper()
Q8. What does the find() method return if a substring is not found?
A. 0
B. None
C. -1
D. ValueError
Correct Answer: C. -1
Q9. Which method raises a ValueError if the specified substring is not found?
A. find()
B. index()
C. count()
D. replace()
Correct Answer: B. index()
Q10. Which method splits a string into a list?
A. join()
B. replace()
C. split()
D. strip()
Correct Answer: C. split()
Q11. What is the output of the following code?
print('hello'.count('l'))
A. 1
B. 2
C. 3
D. 4
Correct Answer: B. 2
Q12. Which method removes leading and trailing whitespace?
A. replace()
B. strip()
C. split()
D. upper()
Correct Answer: B. strip()
Q13. What does 'python'.isalpha() return?
A. True
B. False
C. None
D. Error
Correct Answer: A. True
Q14. What is the output of the following code?
print('hello' in 'hello world')
A. False
B. True
C. None
D. Error
Correct Answer: B. True
Q15. Which method replaces an existing substring with another substring?
A. count()
B. find()
C. replace()
D. index()
Correct Answer: C. replace()