0% found this document useful (0 votes)
23 views6 pages

Chapter 8 Strings

Chapter 8 covers strings in Python, defining them as immutable sequences of characters. It explains how to create, access, and manipulate strings using various operations such as concatenation, repetition, and slicing, as well as built-in methods for string handling. The chapter also includes exercises for practical application of string concepts.

Uploaded by

nagalalitha729
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views6 pages

Chapter 8 Strings

Chapter 8 covers strings in Python, defining them as immutable sequences of characters. It explains how to create, access, and manipulate strings using various operations such as concatenation, repetition, and slicing, as well as built-in methods for string handling. The chapter also includes exercises for practical application of string concepts.

Uploaded by

nagalalitha729
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter 8 Strings

July 28, 2024

Chapter 8: Strings
Introduction to Strings
• Definition: A string is a sequence of characters.
• Strings are immutable in Python, meaning once created, they cannot be changed.

8.1 Creating Strings


• Single Quotes: 'Hello'
• Double Quotes: "Hello"
• Triple Quotes: '''Hello''' or """Hello""" for multi-line strings.
Example:

[ ]: single_line = 'Hello, World!'


multi_line = '''This is
a multi-line
string.'''
print(single_line) # Output: Hello, World!
print(multi_line) # Output: This is\na multi-line\nstring

Explanation: single_line is a simple string using single quotes, while multi_line is a multi-line
string using triple quotes.

8.2 Accessing Characters in a String


• Indexing: Use square brackets [ ] to access individual characters.
– Positive indices start from 0.
– Negative indices start from -1 from the end.
Example:

[ ]: str1 = 'Hello, World!'


print(str1[0]) # Output: 'H'
print(str1[-1]) # Output: '!'
print(str1[7]) # Output: 'W'

Explanation: This program accesses characters in str1 using positive and negative indices.

1
Chapter 8 Strings

8.3 String Operations


8.3.1 Concatenation
• Use + to join two or more strings.
Example:

[ ]: str1 = 'Hello'
str2 = 'World!'
result = str1 + ' ' + str2
print(result) # Output: 'Hello World!'

Explanation: This program joins str1 and str2 with a space in between using the + operator.

8.3.2 Repetition
• Use * to repeat a string multiple times.
Example:

[ ]: str1 = 'Hello'
print(str1 * 2) # Output: 'HelloHello'
print(str1 * 5) # Output: 'HelloHelloHelloHelloHello'

Explanation: This program repeats the string str1 2 and 5 times using the * operator.

8.3.3 Membership
• Use in and not in to check for the presence of a substring.
Example:

[ ]: str1 = 'Hello, World!'


print('W' in str1) # Output: True
print('My' not in str1) # Output: True

Explanation: This program checks if ‘W’ is in str1 and if ‘My’ is not in str1 using the in and
not in operators.

8.3.4 Slicing
• Extract substrings using str1[start:end].
– start is inclusive, end is exclusive.
Example:

[ ]: str1 = 'Hello, World!'


print(str1[1:5]) # Output: 'ello'
print(str1[:5]) # Output: 'Hello'
print(str1[6:]) # Output: ' World!'
print(str1[::2]) # Output: 'Hlo ol!'

PRIMUS PU COLLEGE, BANGALORE | 2


Chapter 8 Strings

Explanation: This program slices str1 to extract substrings using different start, end, and step
values.

8.4 Traversing a String


Using for Loop Example:

[ ]: str1 = 'Hello, World!'


for ch in str1:
print(ch, end=' ')

Explanation: This program uses a for loop to iterate over each character in str1 and print them
with a space in between.

Using while Loop Example:

[ ]:

[ ]: str1 = 'Hello, World!'


index = 0
while index < len(str1):
print(str1[index], end=' ')
index += 1

Explanation: This program uses a while loop to iterate over each character in str1 and print them
with a space in between.

8.5 String Methods and Built-in Functions


len(): Returns the length of the string. Example:

[ ]: print(len('Hello'))

title(): Converts the first character of each word to uppercase. Example:

[ ]: print('hello world'.title()) # Output: 'Hello World'

Explanation: This method capitalizes the first letter of each word in the string ‘hello world’.

lower(): Converts all characters to lowercase. Example:

[ ]: print('HELLO'.lower()) # Output: 'hello'

Explanation: This method converts all characters in the string ‘HELLO’ to lowercase.

upper(): Converts all characters to uppercase. Example:

[ ]: print('hello'.upper()) # Output: 'HELLO'

Explanation: This method converts all characters in the string ‘hello’ to uppercase.

PRIMUS PU COLLEGE, BANGALORE | 3


Chapter 8 Strings

count(): Counts occurrences of a substring. Example:

[ ]: print('hello'.count('l')) # Output: 2

Explanation: This method counts the number of times ‘l’ appears in the string ‘hello’.

find(): Finds the first occurrence of a substring. Example:

[ ]: print('hello'.find('e')) # Output: 1

Explanation: This method returns the index of the first occurrence of ‘e’ in the string ‘hello’.

index(): Finds the first occurrence of a substring (raises error if not found). Example:

[ ]: print('hello'.index('e')) # Output: 1

Explanation: This method returns the index of the first occurrence of ‘e’ in the string ‘hello’. If ‘e’
is not found, it raises a ValueError.

endswith(): Checks if the string ends with a specified substring. Example:

[ ]: print('hello'.endswith('o')) # Output: True

Explanation: This method returns True if the string ‘hello’ ends with ‘o’, otherwise it returns
False.

startswith(): Checks if the string starts with a specified substring. Example:

[ ]: print('hello'.startswith('h')) # Output: True

Explanation: This method returns True if the string ‘hello’ starts with ‘h’, otherwise it returns
False.

isalnum(): Checks if all characters are alphanumeric. Example:

[ ]: print('hello123'.isalnum()) # Output: True

Explanation: This method returns True if all characters in the string ‘hello123’ are alphanumeric,
otherwise it returns False.

islower(): Checks if all characters are lowercase. Example:

[ ]: print('hello'.islower()) # Output: True

Explanation: This method returns True if all characters in the string ‘hello’ are lowercase, otherwise
it returns False.

PRIMUS PU COLLEGE, BANGALORE | 4


Chapter 8 Strings

isupper(): Checks if all characters are uppercase. Example:

[ ]: print('HELLO'.isupper()) # Output: True

Explanation: This method returns True if all characters in the string ‘HELLO’ are uppercase,
otherwise it returns False.

isspace(): Checks if all characters are whitespace. Example:

[ ]: print(' '.isspace()) # Output: True

Explanation: This method returns True if all characters in the string ’ ’ are whitespace, otherwise
it returns False.

istitle(): Checks if the string is title-cased. Example:

[ ]: print('Hello World'.istitle()) # Output: True

Explanation: This method returns True if the string ‘Hello World’ is title-cased, otherwise it returns
False.

lstrip(): Removes leading whitespace. Example:

[ ]: print(' hello'.lstrip()) # Output: 'hello'

Explanation: This method removes leading whitespace from the string ’ hello’.

rstrip(): Removes trailing whitespace. Example:

[ ]: print('hello '.rstrip()) # Output: 'hello'

Explanation: This method removes trailing whitespace from the string ‘hello’.

strip(): Removes both leading and trailing whitespace. Example:

[ ]: print(' hello '.strip()) # Output: 'hello'

Explanation: This method removes both leading and trailing whitespace from the string ’ hello ’.

replace(): Replaces a substring with another. Example:

[ ]: print('hello'.replace('l', 'x')) # Output: 'hexxo'

Explanation: This method replaces all occurrences of ‘l’ with ‘x’ in the string ‘hello’.

join(): Joins elements of an iterable with a string separator. Example:

[ ]: print('-'.join('hello')) # Output: 'h-e-l-l-o'

Explanation: This method joins the characters of the string ‘hello’ with ‘-’ as a separator.

PRIMUS PU COLLEGE, BANGALORE | 5


Chapter 8 Strings

partition(): Splits the string into three parts. Example:

[ ]: print('hello world'.partition(' ')) # Output: ('hello', ' ', 'world')

Explanation: This method splits the string ‘hello world’ at the first occurrence of ’ ’ into a tuple
containing the part before the separator, the separator itself, and the part after the separator.

split(): Splits the string at the specified separator. Example: ‘

[ ]: print('hello world'.split(' ')) # Output: ['hello', 'world']

Explanation: This method splits the string ‘hello world’ at each occurrence of ’ ’ into a list of
substrings.

Exercises
1. Write a Python program to find the length of a string.

[ ]:

2. Write a Python program to count the number of times a character appears in a string.

[ ]:

3. Write a Python program to check if a string is a palindrome.

[ ]:

[ ]:

4. Write a Python program to convert a string to uppercase without using the upper() method.

[ ]:

5. Write a Python program to remove all whitespace from a string.

[ ]:

6. Write a Python program to reverse the order of words in a string.

[ ]:

7. Write a Python program to find the most common character in a string.

[ ]:

8. Write a Python program to find the first non-repeating character in a string.

[ ]:

PRIMUS PU COLLEGE, BANGALORE | 6

You might also like