Table of contents |
|
Introduction |
|
Strings in Python |
|
String Operations |
|
Traversing a String |
|
String Methods and Built-In Functions |
|
Handling Strings in Python |
|
We learned that a sequence is an organized collection of items, with each item indexed by an integer. We also got a brief introduction to various sequence data types in Python, including:
Additionally, we were introduced to the Dictionary data type, which falls under the category of mapping. In this chapter, we will explore strings in detail.
A string in Python is a collection of one or more Unicode characters. These characters can be letters, digits, whitespace, or any other symbols. To create a string, you can enclose characters in single, double, or triple quotes.
Example:
str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!"""
str4 = '''Hello World!'''
In this example, str1, str2, str3, and str4 all contain the same string value, 'Hello World!'. The values in str3 and str4 can span multiple lines because they are enclosed in triple quotes.
For instance:
str3 = """Hello World! welcome to the world of Python"""
str4 = '''Hello World! welcome to the world of Python'''
Python does not have a separate character data type; a string of length one is considered a character.
Indexing is the method used to access individual characters within a string. The index indicates which character to retrieve from the string and is enclosed in square brackets ( [ ] ). In Python, the index of the first character (from the left) is 0, while the index of the last character is n-1, where n is the length of the string. If an index outside this range is specified, an IndexError will occur. The index must be an integer, which can be positive, zero, or negative.
Example:
Initializing a string
Using Expressions for Indexing
Negative Indexing
Using the len() Function
Accessing Characters Using Length
In Python, strings are considered immutable data types. This means that once a string is created, its contents cannot be changed. If you try to modify a string after it has been created, it will result in an error.
For example, if we have a string str1 = "Hello World!" and we attempt to replace the character 'e' with 'a' using str1[1] = 'a', Python will raise a TypeError because strings do not support item assignment.
Introduction: Python permits various operations on strings, including concatenation, repetition, membership, and slicing. A string is essentially a sequence of characters, and these operations allow for different ways to manipulate and interact with string data.
Concatenation refers to the process of joining two strings together. In Python, this can be done using the concatenation operator, which is the plus sign ( + ).
Example:
Code:
str1 = 'Hello' # First string str2 = 'World!' # Second string result = str1 + str2 # Concatenated strings print(result)
Output:
'HelloWorld!'
Explanation:
Example:
Code:
print(str1) # Output: 'Hello' print(str2) # Output: 'World!'
Repetition in Python allows you to repeat a given string multiple times using the repetition operator, which is denoted by the symbol *.
Example:
Code:
str1 = 'Hello' # Repeat the value of str1 2 times result1 = str1 * 2 print(result1) # Repeat the value of str1 5 times result2 = str1 * 5 print(result2)
Output:
'HelloHello' 'HelloHelloHelloHelloHello'
Explanation:
In Python, there are two membership operators: 'in' and 'not in'. These operators are used to check whether a substring exists within a string.
'in' Operator
For example:
Example:
str1 = "Welcome to my world"
'not in' Operator
For example:
Example:
str1 = "Welcome to my world"
Step Size in Slicing
Negative Indexing in Slicing
We can access or traverse each character of a string using either a for loop or a while loop.
(A) String Traversal Using for Loop:
Output: Hello World!
(B) String Traversal Using while Loop:
Output: Hello World!
Python offers various built-in functions for working with strings. The table below outlines some of the commonly used built-in functions for string manipulation.
Built-in Functions for String Manipulation
In this section, we will explore user-defined functions in Python that allow us to perform various operations on strings. Strings are a fundamental data type in Python, and understanding how to manipulate them using functions can greatly enhance our programming skills.
Let's delve into a specific program that demonstrates how to count the occurrences of a character in a given string using a user-defined function.
Program: Write a program with a user defined function to count the number of times a character (passed as argument) occurs in the given string.
Output:
Enter a string:
Today is a Holiday Enter the character to be searched: a Number of times character a occurs in the string is: 3
Program: Write a program with a user defined function with string as a parameter which replaces all vowels in the string with '*'.
Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
Program: Write a program to input a string from the user and print it in the reverse order without creating a new string.
Program: Write a program which reverses a string passed as parameter and stores the reversed string in a new string. Use a user defined function for reversing the string.
Program: Write a program using a user defined function to check if a string is a palindrome or not. (A string is called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.)
33 docs|11 tests
|
1. What are strings in Python and how are they defined? | ![]() |
2. What are some common operations that can be performed on strings in Python? | ![]() |
3. How can you traverse a string in Python? | ![]() |
4. What are some commonly used string methods in Python? | ![]() |
5. How do built-in functions interact with strings in Python? | ![]() |