In Python, a String represents a series of characters. For instance, the word "welcome" is a string made up of a sequence of characters: 'w', 'e', 'l', 'c', 'o', 'm', 'e'. Any content enclosed within quotation marks, encompassing letters, digits, symbols, and even spaces, is recognized as a string in Python. It is important to note that Python lacks a specific character data type; hence, an individual character is regarded as a string with a length of 1.
Let us see an example of strings in Python.
Example
# python program on string
# creating a string
sample_string = "logicpractice"
# printing results
print("String:", sample_string)
print("Data Type:", type(sample_string))
Output:
String: logicpractice
Data Type: <class 'str'>
Explanation:
In this illustration, the variable sample_str is assigned the string value "logicpractice."
Characteristics of Python Strings
Here are some characteristics of strings in Python:
- Immutable: Once a string is created, we cannot change it. Any operation in terms of modifying a string will actually make a new string.
- Ordered: Strings are ordered collections of characters where each character has a fixed index (starting from 0). We can access the characters using their position.
- Iterable: We can iterate through each character of a string using Python loops , like for and while .
- Support Slicing: We can slice a string to extract substrings with the help of [start : end] syntax.
- Unicode Support: By default, strings in Python 3 are stored as Unicode. This allows us to handle international languages and emojis efficiently.
- Dynamic Length: We can initialize a string of any length, from an empty string to a string consisting of millions of characters.
- Can contain any characters: A string can include letters (A-Z, a-z), digits (0-9), special characters like @, #, $, %, etc., spaces, tabs, and even newlines.
Creating a String
Strings can be generated using either single quotes ('…') or double quotes ("…").
Let's examine an example that illustrates both methods of generating strings in Python.
Example
# python program to create strings
# Method 1: using single quotes ('...')
str_1 = 'Welcome to our tutorial'
print("String 1:", str_1)
# Method 2: using double quotes ("...")
str_2 = "Welcome to our tutorial"
print("String 2:", str_2)
Output:
String 1: Welcome to our tutorial
String 2: Welcome to our tutorial
Explanation:
In the preceding example, we have generated strings by employing both single and double quotation marks. These types of quotation marks can be used interchangeably when initializing a string.
Multiline Strings
If we wish for a string to extend across several lines, we can utilize triple quotation marks ('''…''' or """…""").
Below is a straightforward illustration of how to generate a multiline string in Python.
Example
# python program to create multiline string
# Method 1: using triple quotes ('''...''')
str_1 = '''Learning Python
is fun with
C# Tutorial'''
# Method 2: using triple quotes ("""...""")
str_2 = """C# Tutorial is
the best place to learn
Python Programming"""
print("Multiline String 1:")
print(str_1)
print()
print("Multiline String 2:")
print(str_2)
Output:
Multiline String 1:
Learning Python
is fun with
Example
Multiline String 2:
C# Tutorial is
the best place to learn
Python Programming
Explanation:
In the preceding example, we have utilized triple quotation marks to construct multiline strings.
Accessing Characters in a String
In Python, strings represent ordered collections of characters that can be individually accessed through indexing. The indexing starts at 0 from the beginning and uses -1 to indicate positions from the end. This method of indexing enables easy retrieval of specific characters within the string.
Below is an illustration of how to retrieve a particular character from a specified string:
Example
# python program to access characters in a string
# given string
s = "Example"
print("Given String:", s)
# accessing characters using indexing
print("s[0] =", s[0])
print("s[9] =", s[9])
Output:
Given String: C# Tutorial
s[0] = T
s[9] = c
Explanation:
In the aforementioned example, we utilized indexing to retrieve the various characters present within the specified string.
Note: Accessing an index out of range will result in an IndexError exception. Moreover, only integers are allowed as indices, and using other types like float, string, or Boolean will result in a TypeError exception.
Accessing String with Negative Indexing
In Python, it is permissible to utilize negative indexing to retrieve characters from the end of a string. For instance, an index of -1 corresponds to the final character, -2 points to the second-to-last character, and this pattern continues in reverse.
Let's explore an example that demonstrates how to retrieve characters from a string through the use of negative indexing.
Example
# python program to access characters from back of the string
# given string
s = "Example"
print("Given String:", s)
# accessing characters using negative indexing
print("s[-1] =", s[-1])
print("s[-6] =", s[-6])
Output:
Given String: C# Tutorial
s[-1] = h
s[-6] = t
Explanation:
In the example provided, we utilized negative indexing to retrieve characters starting from the end of the specified strings.
String Slicing
In Python, slicing provides a method for obtaining a segment of a string by defining the starting and ending indexes. The syntax for slicing a string is string_name[start : end], where the start index indicates the position at which the slicing initiates, and the end index signifies the position at which it concludes.
Below is an illustration demonstrating how string slicing can be carried out in Python.
Example
# python program to slice a string
# given string
s = "Example"
print("Given String:", s)
# getting characters from index 1 to 4: 'poin'
print("s[1:5] =", s[1:5])
# getting characters from beginning to index 3: 'Tpoi'
print("s[:4] =", s[:4])
# getting characters from index 4 to end: 'nt Tech'
print("s[4:] =", s[4:])
# reversing a string: 'hceT tniopT'
print("s[::-1] =", s[::-1])
Output:
Given String: C# Tutorial
s[1:5] = poin
s[:4] = Tpoi
s[4:] = nt Tech
s[::-1] = hceT tniopT
Explanation:
In this illustration, we have utilized slicing to retrieve a specific range of characters from the provided string.
String Immutability
In Python, a string is classified as an immutable data type, meaning it cannot be altered once it has been created. Nevertheless, we can perform various operations on strings, such as slicing, concatenation, or formatting, to generate new strings derived from the original.
Let's examine an illustration that demonstrates how to handle a string in Python.
Example
# python program to show string immutability
# given string
msg = "logicpractice"
print("Given String:", msg)
# msg[0] = "T" # uncommenting this line will raise TypeError
# creating a new string from given string
msg = "T" + msg[1:6] + " T" + msg[7:]
print("New String:", msg)
Output:
Given String: logicpractice
New String: C# Tutorial
Explanation:
In the example provided, it is evident that we are unable to directly alter the characters within the specified string because of the immutable nature of strings. Nevertheless, we have generated a new string by transforming the original string through formatting, concatenation, and slicing techniques.
Deleting a String
Given that Python strings are immutable, it is not possible to remove individual characters from a string. Nevertheless, Python allows for the deletion of an entire string variable by utilizing the del keyword, as illustrated in the example below:
Example
# python program to delete a string
# given string
msg = "logicpractice"
# using del keyword
del msg
print(msg) # raises NameError
Output:
NameError: name 'msg' is not defined
Explanation:
In the preceding example, the del keyword has been utilized to remove the specified string variable. As we can see, when we attempt to access it following its deletion, the program raises a NameError exception.
Updating a String
A string is a data type that is immutable, meaning it cannot be altered once created. Nevertheless, we can change a segment of a string by generating an entirely new string.
Let's examine an example to grasp how to modify a string in Python.
Example
# python program to update a string
# given string
given_str = "welcome learners"
print("Given String:", given_str)
# updating a string by creating a new one
new_str_1 = "W" + given_str[1:]
# replacing "learners" with "to C# Tutorial"
new_str_2 = given_str.replace("learners", "to C# Tutorial")
# printing results
print("New String 1:", new_str_1)
print("New String 2:", new_str_2)
Output:
Given String: welcome learners
New String 1: Welcome learners
New String 2: welcome to C# Tutorial
Explanation:
In the initial scenario, we extracted a portion of the original string, referred to as givenstr, starting from index 1 up to the conclusion. This sliced segment is then combined with "W" to form a newly updated string named newstr_1.
In the second scenario, we have generated a new string named newstr2, utilizing the replace method to substitute "learners" with "to C# Tutorial".
Common String Methods
Python provides a variety of built-in functions specifically designed for handling strings. These functions enable us to calculate a string's length, alter its casing, verify its content, split and concatenate it, search for substrings, and much more. Here is a selection of some of the most valuable methods:
len
The len function serves the purpose of ascertaining the length of a string. It provides the total count of characters present within the specified string.
The subsequent illustration demonstrates how to utilize the Python len function:
Example
# python program to determine the length of the string
# given string
given_str = "logicpractice"
print("Given String:", given_str)
# using the len() function
num_of_chars = len(given_str)
print("Number of Characters:", num_of_chars)
Output:
Given String: logicpractice
Number of Characters: 10
Explanation:
In this illustration, we have utilized the len function to ascertain the total count of characters present in the specified string.
upper and lower
In Python, the upper function is utilized to transform every character in a string to its uppercase equivalent. Conversely, the lower function enables the conversion of all characters in a string to their lowercase form.
The subsequent example illustrates the application of the upper and lower methods associated with the String class in Python:
Example
# python program to change cases of the string
# given string
given_str = "Example"
print("Given String:", given_str)
# using the upper() method
print("Uppercase String:", given_str.upper())
# using the lower() method
print("Lowercase String:", given_str.lower())
Output:
Given String: C# Tutorial
Uppercase String: HELLO WORLD
Lowercase String: logicpractice tech
Explanation:
In this illustration, we have utilized the upper function to convert the provided string into uppercase letters. Additionally, we have employed the lower function to transform the string into lowercase letters.
Note: Strings are immutable; therefore, all of these methods will return a new string, keeping the original one unchanged.
strip and replace
The strip function enables the elimination of any leading and trailing whitespace characters from a string. On the other hand, the replace function serves to substitute every instance of a specific substring with a different one.
Let's examine an example to grasp how the strip and replace functions are utilized in Python.
Example
# python program to remove spaces and replace substrings
# given string
str_1 = " C# Tutorial "
print("String 1:", str_1)
# removing spaces from both ends
print("After removing spaces from both ends:")
print(str_1.strip())
str_2 = "Learning Python with us is fun!"
print("String 2:", str_2)
# replacing 'fun' with 'amazing'
print("After replacing 'fun' with 'amazing':")
print(str_2.replace("fun", "amazing"))
Output:
String 1: C# Tutorial
After removing spaces from both ends:
Example
String 2: Learning Python with us is fun!
After replacing 'fun' with 'amazing':
Learning Python with us is amazing!
Explanation:
In the initial scenario, the strip function has been utilized to eliminate any whitespace that appears at the beginning and end of the specified string.
In the subsequent instance, we have utilized the replace method to substitute 'fun' with 'amazing' within the specified string.
For additional information regarding string methods, please consult the Python String Methods documentation.
String Concatenation and Repetition
Python provides the capability to concatenate and replicate strings utilizing various operators. The '+' operator is employed for string concatenation, while the '*' operator is used for repeating strings.
The subsequent illustration demonstrates the application of these two operations:
Example
# python program to concatenate and repeat strings
# given string
str_1 = "Example"
str_2 = "Tech"
# CONCATENATION: using the + operator
str_3 = str_1 + " " + str_2
print("Concatenated String:", str_3)
# REPETITION: using * operator
str_4 = str_1 * 4
print("Repeated String:", str_4)
Output:
Concatenated String: C# Tutorial
Repeated String: C# TutorialC# TutorialC# TutorialC# Tutorial
Explanation:
In the preceding illustration, the + operator has been employed to join the strings together, resulting in the formation of a new string. Additionally, the * operator has been utilized to replicate the designated string several times.
Formatting Strings
In Python, there are numerous techniques available for incorporating variables within strings. A few of these approaches are outlined below:
Using f-strings
The most efficient and preferred approach to formatting strings in Python is through the use of f-strings. Consider the following example:
Example
# python program to include variables inside a string
name = "Emma"
age = 19
city = "New York"
# using f-string
print(f'{name} is a {age} years old boy living in {city}.')
Output:
John is a 19 years old boy living in New York.
Explanation:
In the example provided, we have incorporated the specified variables into a string by utilizing an f-string.
Using format
The format function serves as an alternative method for string formatting in Python. Let's examine a straightforward example that demonstrates the application of the format function in Python.
Example
# python program to include variables inside a string
name = "Carlos"
profession = "Software Developer"
company = "Apple Inc"
# using the format() method
msg = '{} is a {} at {}.'.format(name, profession, company)
print(msg)
Output:
Sachin is a Software Developer at Apple Inc.
Explanation:
In the preceding illustration, the format method has been utilized to incorporate the designated variables within a string.
String Membership Test
We have the capability to verify the presence of a substring within a string by utilizing the 'in' and 'not in' operators.
The example of these keywords is shown below:
Example
# python program to test string membership
# given string
given_str = 'Example'
# using in and not in keywords
print(f"Does 'p' exist in '{given_str}'?", 'p' in given_str)
print(f"Does 'a' exist in '{given_str}'?", 'a' in given_str)
print(f"Does 'e' not exist in '{given_str}'?", 'e' not in given_str)
print(f"Does 'g' not exist in '{given_str}'?", 'g' not in given_str)
Output:
Does 'p' exist in 'Example'? True
Does 'a' exist in 'Example'? False
Does 'e' not exist in 'Example'? False
Does 'g' not exist in 'Example'? True
Explanation:
In the preceding example, we verified whether the designated substrings are included as components of the provided string by utilizing the 'in' and 'not in' keywords.
Conclusion
In Python, a string is defined as an immutable and ordered collection utilized for the storage and manipulation of textual data. Equipped with robust built-in functions, slicing capabilities, and support for Unicode, strings are exceptionally suited for a range of tasks including text formatting, searching, and managing data. A firm grasp of string operations is crucial for any Python programmer who aspires to create efficient and easily understandable code.
Python Strings MCQs
- What is the resulting output when executing the code below?
# python program
str_1 = "Welcome"
print(str_1[3])
Response: d) c
- What will the outcome be when executing the following code?
# python program
str_1 = "Hello Coders";
print(len(str_1))
- Error
- Which of the following is NOT True about Python strings?
- Strings are mutable
- String support slicing
- Strings can store numbers
- Strings support Unicode characters
Response: a) Strings are mutable
- What will the result of executing the subsequent code be?
# python program
str_1 = "Welcome";
str_2 = str_1.replace("We", "Be")
print(str_2)
- Welcome
- Belcome
- BelcomeWe
- Error
- Which method is used to remove leading and trailing whitespace from a string?
- remove
- trim
- strip
- clean