Home Icon Home Resource Centre Python Strings | Create, Format, Reassign & More (+Examples)

Python Strings | Create, Format, Reassign & More (+Examples)

Python strings are an immutable data type facilitating the manipulation of textual data in Python programs. We can create them with single, double, and triple quotes and perform a variety of operations on them.
Shivani Goyal
Schedule Icon 0 min read
Python Strings | Create, Format, Reassign & More (+Examples)
Schedule Icon 0 min read

Table of content: 

  • What Is A String In Python?
  • Creating String In Python
  • How To Create Multiline Python Strings?
  • Reassigning Python Strings
  • Accessing Characters Of Python Strings
  • How To Update Or Delete A Python String?
  • Reversing A Python String
  • Formatting Python Strings
  • Concatenation & Comparison Of Python Strings
  • Python String Operators
  • Python String Functions
  • Escape Sequences In Python Strings
  • Conclusion
  • Frequently Asked Questions
expand icon

Python, a versatile and powerful programming language, comes with an array of features, making it one of the most popular languages. One such aspect that adds to the uniqueness of the language is  Python strings. They refer to a fundamental data type that represents a sequence of characters. Whether you're a beginner or an experienced developer, understanding the concept of strings is essential for effective programming. In this article, we'll explore the basics of Python strings and delve into advanced techniques to help you master this crucial aspect of the language.

What Is A String In Python?

A string in Python language is an immutable object, i.e., contents in the string cannot be changed once it is created. However, you can perform various operations on strings, such as concatenation, formatting, searching for a substring, etc. Strings in all programming languages are used to represent sequences of characters. But Python distinguishes itself by providing a convenient and expressive syntax for working with strings.

While, on one hand, languages like C and C++ require manual memory management for string manipulation, language like Java has immutable strings, similar to Python. However, they still differ in syntax and available methods. 

In Python, we can declare strings using single quotes, double quotes, and even triple quotes. They also have the concept of multiline strings, all of which we will discuss ahead. But first, let's take a look at the syntax for declaring Python strings.

Syntax:

my_string = ‘string in python’
my_string = “string in python”
my_string = ‘“string in python’’’

Example:

my_string = ‘ Hello world!’
my_string = “ Python Strings”

Creating String In Python

As we've mentioned before, to create a Python string, the set of characters must be enclosed in single quotes/ double quotes and then be assigned to a variable. Below is a simple example of the same. 

Code:

Output:

Hello World!
Creating a string in Python
Python Strings
This is a “quoted” string

Code Explanation:

In the code example above-

  1. We define a variable called my_string and use the single quote method to assign the phase/ sequence 'Hello, World!' to it.
  2. And then, we display the string to the console using the print() function
  3. Note that since Python is a dynamically typed language, we do not need to declare the data type for these variables beforehand. 
  4. Then, we define another variable called string_name and use the double quotes method to assign the string-  Creating a string in Python - to it. This is also printed to the output window using print.
  5. After that, we use the triple quotes method to assign the string- Python Strings - to the variable string_name and print it to the console. 
  6. Lastly, we create a string to showcase the use of escape character backslash (\) to show how to include special characters. For this, we declare a variable message and equate it to the phrase- This is a "quoted'' string.
  7. This is also printed to the console using the print() function.

Assign Python String To A Variable

Breakup of syntax for Python string declaration, initialization and printing.

When assigning a string to a variable in Python, you are essentially storing the string value in memory and associating it with a variable name. Here are some important details about assigning a string to a variable.

  • Variable Declaration: In Python, you don't need to explicitly declare the variable type. You can directly assign a string value to a variable without specifying its data type.
  • Syntax: The syntax for assigning a string to a variable is straightforward. You use the assignment operator (=) to assign the string value to the variable name.
    Example: my_string = "Hello World!"
  • Variable Naming: When naming a variable, you must adhere to a few requirements. For example, the variable names can consist of letters (both uppercase and lowercase), digits, and underscore ( _ ). However, they cannot start with a digit and should be descriptive and meaningful.
  • String Manipulation: Once a string is assigned to a variable, it can be manipulated in various string methods or operations. We can modify the strings, concatenate the strings, and can access individual substrings, etc.

Code Example:

Output:

Welcome to Python Programming with Unstop!

Code Explanation:

  1. In this example, first, we declare a variable my_string and assign the string value to it using the double quotes method. 
  2. Next, we use the print() function to display the value of the variable my_string.

How To Find Length Of Python Strings?

In Python programming, we use the len() function to find out the length of a string. The length of the entire string represents the number of characters that are present in it. That is, the string length refers to an integer value that represents the total count of characters in the string, including spaces and a list of characters (special).

Example:

Output:

5

Code Explanation:

In the given sample Python program,

  1. We start by declaring a variable called my_string and assign the string value Hello to it using single quotes. 
  2. Next, we use the len() function inside a print() function. The len() function first finds the length of the my_string variable, which is a parameter here. 
  3. And the print() function outputs this value to the console. 
  4. Here, the string Hello has 5 characters, i.e., H, e, l, l, and o.

How To Create Multiline Python Strings?

Creating multi-line strings in Python provides better readability and flexibility. In this language, you can either use three single quotes ('''), three double quotes ("""), brackets, or backslashes to create this type of string. What is amazing is that when using these methods, you don't need to worry about the white space/ spacing between the strings.

  • When using three single or three double quotes, escape characters like newline (\n) and tab space (\t) become part of the string, maintaining the formatting.
  • This is useful for preserving line breaks and indentation in code or text.
  • The join() function can also be used to create multiline strings without worrying about white spaces or double spaces between the strings. This function concatenates a list of strings, using a specified delimiter to form a multiline string.

Now, let's take a look at examples that showcase the use of these methods to create multiline Python strings. 

Code Example 1: Using Triple Single Quotes (''') For Multiline Python String

Output:

This is a multiline string
using triple single quotes.
It preserves line breaks and indentation.

Code Explanation:

In this Python program-

  1. We first declare a variable called multiline_string and assign a sequence of characters to it using the triple single quotes method (''').
  2. This allows us to write the string across multiple lines while preserving line breaks and indentation.
  3. Next, we use the print() function to display the content of the multiline_string to the console.

Code Example 2: Using Triple Double Quotes (""") For Multiline Python String

Output:

This is a multiline string
using triple double quotes.
It maintains line breaks and indentation.

Code Explanation:

  1. We first declare a variable called multiline_string2 using the triple double quotes method and assign the same string as in the example before.
  2. This method also allows us to write the string across multiple lines while preserving line breaks and indentation.
  3. Finally, we use the print() function to display the content of the multiline_string2.

Code Example 3: Using Backslash (\) For Line Continuation In Multiline Python String

Output:

This is a multiline string using line continuation.
It continues the string on the next line.

Code Explanation:

In this example-

  1. We start by defining a string variable called multiline_string3 and assign string values to it using regular double quotes.
  2. Next, we use the backslash (\) at the end of the first line to indicate line continuation and continue the string on the next line.
  3. Finally, we use the print() function that prints the output of multiline_string3.

Reassigning Python Strings

Example of reassigning python string, with one new character.

Reassigning strings in Python involves changing the value associated with a string variable. Strings are immutable in Python, meaning their contents cannot be modified directly. However, you can reassign a new value to the same variable, effectively creating a new string. This flexibility allows you to update or modify the string value as needed during program execution using the assignment operator (=).

  • When you reassign a string, a new string object is created in memory with the updated value, while the original string remains unchanged.
  • Reassigning strings enables you to maintain a consistent variable reference while updating the string content.

Here's a small example that demonstrates how to reassign strings in Python.

Code Example:

Output:

Python Strings with Unstop!

Code Explanation:

  1. In this example, we first declare a string variable called my_string and assign the string of characters- "Hello World!" to it using the double quotes method.
  2. Next, the variable is reassigned with a new string of characters, i.e., "Python Strings!".
  3. Here, the variable my_string now holds the new value after the reassignment. Note- This demonstrates how you can update the content of a string by reassigning a new value to the same variable.
  4. Finally, we use the print() function to print the reassigned value of the string in the output window.

Accessing Characters Of Python Strings

Accessing single character of Python strings for replacement or manipulation.

The process to access string characters in Python involves using indexing to retrieve specific characters from a string. That is, each character in the string is assigned a position starting from 0, which is referred to as its index value.

  • Positive indexing allows you to access characters from the beginning of the string, while negative indexing starts from the end.
  • We can extract any character (for comparison, conversion, or manipulation) of the Python string using square brackets and the corresponding index value.
  • There are three ways to use index values to access string characters, i.e., indexes, string slicing method, and loops.
  • This capability enables interaction with specific elements of the string, facilitating tasks such as extracting substrings or modifying characters based on program needs.

In this section, we will discuss all three ways of accessing one or multiple elements of Python strings, along with examples.

Accessing Characters of Python String Using Indexing 

Indexing in Python refers to the process of accessing individual elements within a string, list, or other sequence-like objects. Each element is assigned a unique index, starting from 0 for the first element.

By using square brackets and specifying the index position, you can retrieve a specific element from the sequence. Indexing allows for direct access to elements based on their position, enabling tasks such as extracting characters from a string or retrieving values from a list.

Example Program:

Output:

J
h

Code Explanation:

  1. In this code, we first declare a string variable called name and assign the string John to it using double quotes.
  2. Next, we use the square brackets and the index values with the print() function to access characters. This method lets us get the right of entry to character characters inside a string.
  3. In the line print(name[0]), we're accessing the character at index 0 of the string. In Python, indexing starts from 0, so the character at index zero is the first character of the string.
  4. So, the output of this line will be J, as J is the first character of the string John.
  5. Similarly, in the line print(name[2]), we are accessing the character at index 2 of the string name.
  6. The print functions output the corresponding character to the output window. 

The Slicing Method To Access Python String Characters

The string slicing method in Python allows you to extract a subset of elements from a string, list, or other sequence-like objects. It is achieved by specifying a range of indices using the slice syntax, which uses a colon (:) to separate the start and end positions.

Slice Syntax:

string_name[start:end]

Here,

  • string_name refers to the name of the string variable.
  • Parameters start and end refer to the index values from where you want to begin and end, respectively.

The resulting sliced sequence includes elements from the start index up to, but not including, the end index. The string slicing method provides a convenient way to retrieve substrings or sublists, enabling you to work with specific portions of the original sequence.

Example Program:

Output:

Hello
World!

Code Explanation:

  1. In the above example program, we first declare a  string variable named my_string and assign the value "Hello World!" to it.
  2. Next, we use the print() function with the slicing syntax to access and print segments of the original string.
  3. In the line print(my_string[0:5]), we are slicing the string my_string from index 0 to index 5. This means we are extracting the characters starting from index 0 up to, but not including, index 5. Here, the output will be Hello.
  4. Similarly, in the line print(my_string[6:]), we are slicing the string my_string from index 7 to the end of the string. Hence, the output will be World!.

Using Loops To Access Python String Characters

Loops, such as the for loop in Python, provide a way to iterate over a sequence of elements. In the context of strings, loops can be used to access individual characters one at a time. By iterating through each character in a string, you can perform specific operations or apply logic to each character individually. Let's take a look at an example of the same for better understanding.

Example Program:

Output:

U
n
s
t
o
p

Code Explanation:

In this example program-

  1. First, we declare a string variable named message and assign the value Unstop to it using the double quotes method.
  2. Then, we initiate a for-loop to iterate over each character of the string variable.
  3. The loop iterates over the string message character by character. In each iteration, the current character is assigned to the variable char.
  4. The loop body then executes the print() function, which prints the current character.
  5. During the first iteration, the value of the char is U, which is printed to the console. The process continues until the last character of the string is printed, and the loop terminates. 
  6. As you can see in the output window, every character of the string is printed on a separate line.

How To Update Or Delete A Python String?

While we know that Python strings are immutable, that is, we cannot change their values once they have been created; we can still update or delete them.

  • The process for updating Python strings involves creating a new string with desired modifications.
  • Note that this is not similar to reassigning since here, we are creating a new string variable, not reassigning the value to the original one.
  • You can also concatenate or use string formatting to update the content of a string in Python.
  • Deleting a string is done by using the del keyword to remove the variable reference.
  • However, direct modifications to individual characters within a string are not possible.

Here's an example that demonstrates updating and deleting a string in Python, along with the corresponding output.

Example Code: Updating By Creating A New String

Output:

My name is Jahnvi, and I am 25 years old.

Code Explanation:

In the above example,

  1. First, we create a string variable called name and assign the value Jahnvi to it using double quotes.
  2. We then declare an integer variable called age and assign the value of 25 to it. 
  3. Next, we declare another string variable called my_string and initialize it with a string message. We use string formatting to include the values of the variables name and age in the message. 
  4. Finally, we call the print() function to display the output of my_string, which is ‘My name is Jahnvi, and I am 25 years old’.

Code Example: Deleting A Python String

Output:

# Raises an error: NameError: name 'greeting' is not defined

Code Explanation:

  1. We begin this example by declaring a string variable called greeting and initializing it with Hello.
  2. Then, we proceed to delete the string variable using the del keyword. 
  3. Next, we use the print() function to output the value of the greeting variable. But this will raise a NameError since the variable is no longer defined.

The examples above show how you can update a string by using string formatting with variables and how to delete a string using the del keyword.

Reversing A Python String

Graphic example of reversal of Python string.

Reversing a string in Python involves flipping the order of characters within the given string. This can be achieved using various methods, such as string slicing with a negative stride, utilizing the reversed() function, or iterating through the characters in reverse order. It's worth noting that strings in Python are immutable, so the reversal process creates a new string object, leaving the original string unchanged.

Here's a small example that explains how to reverse a string in Python:

Code:

Output:

!dlroW olleH

Code Explanation:

  1. In this code, we first creat a string variable named string and assign the value Hello World! to it using double quotes.
  2. Next, we create another variable called reversed_string and then reverse the original string using string slicing and a negative stride value of -1.
  3. The slicing syntax [::-1] is used to create a new string that starts from the end of the original string and goes all the way to the beginning, with a step of -1. 
  4. This reversed string version of the original string is assigned to the variable reversed_string.
  5. At last, we use the function print() to print the reversed string to the console.

Formatting Python Strings

Formatting Python Strings | Short example of 3 methods.

Formatting strings in Python involves specifying how textual data should be arranged and presented. It allows you to combine variables, constants, and other data into a cohesive string representation. Python provides several methods for string formatting, including the format() function/ method, the modulus operator (%), and f-strings (formatted string literals).

In this section, we will take a look at what each of these methods entails with the help of code examples.

Using The format() Method To Format Python Strings

The format() method provides a flexible way to format strings by using placeholders and positional or keyword arguments. Here, we use curly brackets inside a string message, which serve as the placeholder for the values we want to insert. These values are then specified by the format() function after the respective string.

Let's take a look at an example for a better understanding of the same.

Example:

Output:

My name is Shivani, and I'm 25 years old.

Code Explanation:

  1. In this example, we first declare a string variable called name and assign the value Shivani to it, using double quotes. 
  2. Next, we declare an integer variable called age and assign the value 25 to it.
  3. Then, we define another string variable, formatted_string, and assign a string message to it.
  4. Within this message, we use the format() method to insert the values of variables, name, and age into the respective curly braces {} in the string.
  5. At last, we use the print() function to display the string message to the console, which is- My name is Shivani, and I'm 25 years old.

Using The Modulus Operator To Format Python Strings

The modulus operator (%), often referred to as the string interpolation operator, allows for simple string formatting with placeholders. The operator with the data type representation acts as a placeholder, signifying the kind of value to be inserted there.

For example, if we want to insert the value of a string variable, the operator will take the form of %s. Here, s represents that the variable is of type string. The variable names, whose values are to be inserted inside the string, are then given at the end inside normal brackets. Take a look at the example below to understand how this is done.

Example:

Output:

My name is Srishti, and I'm 20 years old.

Code Explanation:

  1. In this example, we first declare a variable called name and assign the string value Srishti to it.
  2. We then declare another variable called age and assign the integer value 20 to it.
  3. Next, we define a third variable called formatted_string and assign a formatted string message to it. 
  4. The formatted string is created using the % operator to substitute the values of name and age into the placeholders %s and %d, respectively. The %s is used for string substitution, while %d is used for integer substitution.
  5. Finally, we use the print() function to output the value of the formatted_string variable to the console. 

Using f-strings (Formatted String Literals) To Format Python Strings

Introduced in Python 3.6, f-strings provide a concise and readable way to format strings by embedding expressions inside curly braces. In this method, we use define a formatted string using the letter f before the quote when assigning a string. Inside the string, we use curly brackets with variable names to indicate that the values must be embedded in their place. 

Let's take an example that shows how to use the f-string method to format a Python string.

Example:

Output:

My name is Aman, and I'm 35 years old.

Code Explanation:

  1. In this example, we declare two variables, name and age, and assign values Aman (string with double quotes) and 35 (integer type) to them, respectively. 
  2. We define a third variable called formatted_string and assign a string value to it using the f-string and double quotes method.
  3. The formatted string is created using an f-string by prefixing the string with the letter f. Within the string, curly braces {} are used to enclose the variables- name and age directly.
  4. We then use the print() function to output the value of the formatted_string variable to the console. 

Concatenation & Comparison Of Python Strings

As we have mentioned multiple times before, Python strings are immutable. But we can perform other operations on them, like concatenation and comparison. In this section, we will explore all the ways to get this done. 

Concatenation Of Python Strings

In Python, string concatenation can be performed in two ways, one by using the concatenate operator (+) and the second by using the str.join() method. Both methods allow you to combine two or more strings into a single string. Given below are the examples for both of these methods. 

Code Example 1: Using Concatenate Operator (+)

Output:

Hello world

Code Explanation:

  1. In this example, we first declare two variables, str1 and str2, and assign string values to them.
  2. Next, we use the concatenate operator (+) to join the two strings declared above together.
  3. The space between the two strings is added by including it as a separate string enclosed in double quotation marks.
  4. The output of this operation is stored in a new variable called result.
  5. Finally, we use the print() statement to display the value of the result variable.

Code Example 2: Using str.join() Method

Output:

Hello world

Code Explanation:

  1. In this example, we first declare a variable called str_list, which is a list of strings.
  2. The values are assigned to this variable using the square brackets and double quotes, with values separated by a comma. 
  3. Next, we use the str.join() function to concatenate the strings in the list.
  4. The method takes a list as an argument and joins its elements using the space character, which is called a separator, i.e., " ".join(str_list).
  5. One could use other characters as separators, depending on specific requirements.

It's important to note that this method is particularly useful when you have a list of strings that you want to concatenate. It is more efficient than using the concatenation operator repeatedly, especially when dealing with large lists of strings.

Python String Comparison

In Python, string comparison can be performed in two ways, one by using comparison operators and the second by using the str.compare() method. These methods allow you to compare two strings and determine their relative order or equality.

Here are some common operators used for string comparison:

  1. Equal-to Operator (==): The equality operator checks if two strings are equal.
  2. Not Equal-to Operator (!=): This operator checks for inequality between the strings it is comparing.
  3. Greater-than and Less-than Operators (<)(>): These comparison operators perform lexicographic comparisons to check if one string is less than or greater than another.
  4. Less-than/ Greater-than Equal-to Operators (<=)(>=): These comparison operators check if one string is less than or equal to or greater than or equal to another.

Here is an example of a Python string comparison using the operators listed above. 

Code Example:

Output:

Strings are not equal
str1 is less than str2

Code Explanation:

  1. We begin the example by declaring two variables str1 and str2, and assign string values to them using double quotes.
  2. Next, we initiate an if-else statement and use the equality operator to compare the two strings.
  3. If the strings are equal, then the print() statement in the if block is executed; if not, then the print() statement in the else block is executed.
  4. After that, we conduct a lexicographic comparison between the two string variables using the less than, greater than, and equal to operators. We initiate an if-elif statement where-
    • We employ the less than operator (<) to check if str1 comes before str2 in the dictionary. Since here, apple comes before banana, the condition is true, i.e., str1 is lexicographically less than str2. The if-block is hence executed. 
    • Next, we use the greater than operator (>) to perform an opposite lexicographic comparison. That is, check if str1 comes after str2 in the dictionary, which is false. So, the code block following elif is not executed, and the flow moves on.
    • If both the if and elif conditions had been false, then the code block following the else statement would have been executed. 

Python String Operators

Image with symbols of Python string operators.

In Python, string operators are used to perform various operations on strings. Here are some commonly used string operators in Python:

String operator name

Symbol

Description

Assignment Operator

=

This operator assigns the given value to the string.

Concatenate Operator

+

This operator joins the strings together.

String Repetition Operator

*

This operator repeats the string a specified number of times.

String Slicing Operator

[]

This operator extracts a substring from the original string. This is used with the index values.

String Comparison Operator

==
!=

This operator compares two strings for equality and inequality, respectively.

Membership Operator

in
not in

This operator checks if a substring or character is present or not present in a string.

Escape Sequence Operator

\

This operator represents a special character to the string. It is used to let the interpreter know that the line is continued in the next one.

String Formatting Operator

%
{}

This operator allows formatting strings by replacing placeholders with specified values.

Now, let's take a look at an example that shows the implementation of these operators.

Code Example:

Output:

Assignment Operator: Hello
Concatenate Operator: Hello, World
String Repetition Operator: HelloHelloHello
String Slicing Operator: ell
String Comparison Operator (Equal): False
String Comparison Operator (Not Equal): True
Membership Operator (in): True
Membership Operator (not in): True
Escape Sequence Operator: I'm learning Python.
String Formatting Operator: My name is Jahnvi and I'm 25 years old.

Code Explanation:

In the Python program given above-

  1. We begin by declaring two string variables called str1 and str2. These are initialized with the values Hello and World, respectively, using the double quotes method.
  2. Next, we define another variable called assignment_str and use the assignment operator (=) to assign the value of str1 to it.
  3. Then, using the concatenate operator (+), we join str1 with a comma and space and then str2 together. The result is stored in the string variable concatenated_str.
  4. We define another string variable called repeated_str and use the repetition operator (*) to repeat str1 three times (i.e., str1*3). The result is stored in the repeated_str variable.
  5. Next, we use the slicing operator [] to extract a substring from str1 and store it in a new variable called sliced_str. We start slicing from index 1 (inclusive) and end at index 4 (exclusive).
  6. Then, we use the first comparison operator equal to (==) to compare the value of str1 with str2. This checks for equality, and the result (True or False) is stored in a new variable comparison_result.
  7. The second comparison operator, not equal to (!=), is then used to compare the two original strings for inequality, and the result (True or False) is stored in a new variable, not_equal_result.
  8. After that, the membership operator (in) is used to check if character H is present in str1, and the result (True or False) is stored in the variable membership_result1.
  9. The other membership operator (not in) is used to check if the substring 'foo' is not present in str2. The result (True or False) for this is stored in another variable, membership_result2.
  10. Next, we use the escape sequence operator for apostrophe (\') to include a single quote within the string, and the result is stored in the variable declared as escaped_str.
  11. Then, we use the string formatting operator (%) to format a string message.
    • Here, we use the format specifiers %s and %d, which indicate that the former must be replaced with a string and the latter with integer values.
    • These values are given as Jahnvi and 25 after the double quotes defining the string.
    • The result of this operation is stored in a variable called formatted_str.
  12. Finally, we use the print() function multiple times to display the values of each variable and the results of the operations we have conducted.

Python String Functions

Python string methods/ functions

Python provides a variety of built-in string functions that allow you to manipulate and perform operations on strings. They allow operations such as converting cases (upper/lower), searching for substrings, replacing characters, splitting strings into lists, joining lists into strings, and more.

Python string methods are efficient to use and make the code easier to write as well as implement. Given in the table below are some of the most commonly used string functions in Python, some of which we have also covered in other sections of this blog.

Function Name

Description/ Purpose

Example

len()

Returns the length of the string

len("Hello")
This returns 5

lower()

Converts the string to lowercase

"Hello".lower()
This returns "hello"

upper()

Converts the string to uppercase

"Hello".upper()
This returns "HELLO"

capitalize()

Capitalizes the first character of the first word in a string

"hello".capitalize()
This returns "Hello"

title()

Capitalizes the first character of each word in the string

"hello world".title()
This returns "Hello World"

count()

Returns the number of occurrences of a substring

"Hello, Hello, Hello".count("Hello")
This returns 3

replace()

Replaces a substring (and all its copies) with another substring

"Hello, World".replace("Hello", "Hi")
This returns, "Hi, World"

split()

Splits the string into a list of substrings. It, by default, breaks the string wherever there is a whitespace.

"Hello, World".split(",")
This returns ['Hello', ' World']

join()

Joins elements of a list into a string using a separator.

", ".join(['Apple', 'Banana', 'Orange'])
This returns "Apple, Banana, Orange"

strip()

Removes leading and trailing whitespace

" Hello ".strip()
This returns "Hello"

splitlines()

Splits a multiline string into a list of lines/ strings

multi_line = "Apple\nBanana\nOrange"
Split_list = multi_line.splitlines()
This, when printed, will return a list of individual strings.

startswith()

Check if the string starts with a given string/ character digit

str1 = "How are you doing?"
print("Starts with 'How':", str1.startswith('How'))
The result will be True.

endswith()

Check if the string ends with a given string/ character digit

str1 = "How are you doing?"
print("Ends with '?':", str1.endswith('?'))
The result will be True.

removeprefix()

Removes a given prefix from the string

str2 = "Please, will you do this??"
str2_prefix = str2.removeprefix("Please, ")
This will remove Please and space from the string.

removesuffix()

Removes a given suffix from the string

str2 = "Will you do this??"
str2_suffix = str2.removesuffix("?")
This will remove one question mark.

Now, let's take a look at two examples that showcase how these functions can be implemented and used in Python programs.

Code Example 1:

Output:

Length of the string: 13
The string in lowercase: hello, world!
The string in uppercase: HELLO, WORLD!
Capitalized string: Hello, world!
The string in title case: Hello, World!
Count of 'o': 2
Replaced string: Hello, Unstop!
Split string: ['Hello', ' World!']
Joined string: Hello- World!
Stripped string: Hello, World!

Code Explanation:

We begin this example by declaring a variable called string and assigning the string value - Hello, World! to it, using double quotes.

  1. First, we find out the length of the string-
    • For this, we use the len() function, and the output is stored in another variable, the result.
    • Then, using the print() function, we display the value of the result variable to the console along with a phrase.
  2. Next, as mentioned in the code comments, we convert the string variable into lowercase using the lower() function. The result is stored in the variable lowercase, which is then printed to the console.
  3. We then use the upper() function to convert the string variable to uppercase, and the result is stored in the variable uppercase. We use the print() statement to display this.
  4. After that, we employ the capitalize() function to convert the first character of the first word in the string to a capital letter, and the rest of the characters are converted to lowercase. The result is stored in the capitalized variable and printed to the output window.
  5. Next, using the title() function, we convert the string into title-case format, i.e., capitalize the first character of each word in the string. The rest of the characters in each word are converted to lowercase. This is stored in the new variable called title_case and then printed.
  6. Using the count() function, we then calculate the number of times the substring (here, the character o) occurs/ appears in the original string variable. The result is stored in the variable count, and a print() statement is used to output this value to the console.
  7. Then, we use the replace() function to replace all occurrences of the substring World in the original string with the substring Universe. The result of this manipulation is stored in the variable called replaced, and it is printed to the console.
  8. In the next case, we use the split() function to split the string into a list of substrings using a comma (,) as the separator [i.e., string.split(",")]. The result here is stored in the split_list variable and subsequently printed.
  9. Taking on from the split_list variable, we once again join it using the join() function.
    • Here, we use a hyphen (-) as the separator, but you can use any special character you want for the same.
    • The string resulting from this function is stored in a variable called joined and is displayed to the console using the print() function.
  10. Lastly, we use the strip() function to show how it removes the whitespace. For this-
    • We define another string variable called string2 and assign the same string value to it as the first string variable. But the difference is that we add a whitespace before and after.
    • Then, we use the strip() function on string2 and store the result in the variable called stripped.
    • When we print this, it shows that the leading and trailing whitespaces have been removed from the string.

This example shows how to use the 10 most commonly used Python string functions. But there are more functions that, though not commonly used, do help in manipulating strings in Python.

Code Example 2:

Output:

Line 1
Line 2
Line 3
Splitlines list: ['Line 1', 'Line 2', 'Line 3']
Starts with 'Line': True
Ends with '3': True
Count of 'Hello': 3
Removed prefix: Hello, World!
Removed suffix: Hello, World!

Code Explanation:

In the code above,

  1. We begin by defining a string variable called multiline_string and assign a string to it using double quotes.
  2. Within this string, we use the newline escape character (\n), so when it is printed using the print() function, each element of the string is printed in a new line. The same is shown in the output.
  3. Next, we use the splitlines() function on the variable to split the string into a list of individual strings.
  4. The result of this function implementation is stored in the variable splitlines_list, which is subsequently printed to the console.
  5. After that, we use the startswith() and the endswith() functions on the original string variable.
    • With these, we check if the string begins with substring 'Line' and ends with substring '3', respectively.
    • The result of both these operations is printed to the output window using the print() statements.
  6. Next, we use the count() function to calculate the frequency of a substring. For this-
    • We first define a new string called text and assign the string value 'Hello, Hello, Hello' to it.
    • Then, we use count() to calculate the number of times the substring 'Hello' occurs in the text string (i.e., text.count("Hello")).
    • The resulting number is stored in the variable count, and the same is printed to the console.
  7. After that, the program showcases the use of the removeprefix() function.
    • For this, we first define a string called prefixed_string and assign the value- Prefix Hello, World! to it.
    • Then, we employ removeprefix() on the string to remove the prefix/ substring 'Prefix' from it.
    • The result is stored in the variable removed_prefix, and its value is printed to the console.
  8. Similarly, we use the removesuffix() function by first defining a new string variable, suffixed_string, and assigning the value- Hello, World! Suffix to it.
  9. Then by applying the removesuffix() to this string, we remove the suffix/ substring 'Suffix' from the string. Its result is stored in the variable removed_suffix, and the same is printed to the console.

Escape Sequences In Python Strings

Escape sequences, also known as escape characters, play a crucial role in Python strings. They are special combinations of characters that begin with a backslash (\). These sequences enable the inclusion of difficult-to-type or reserved characters within strings. The table below compiles some commonly used escape characters.

Escape Sequence Description
\\ Backslash (escaped character representing a single backslash)
\' Single quote
\" Double quote
\n Newline (line break)
\t Tab
\b Backspace
\r Carriage return (moves the cursor to the beginning of the line)
\f Form feed (moves the cursor to the next page or clears the screen)
\v Vertical tab
\a Bell (produces a beep sound)
\uXXXX Unicode character (16-bit hexadecimal)
\UXXXXXXXX Unicode character (32-bit hexadecimal)
\xXX Hexadecimal value of a character (ASCII)

These escape sequences are used in strings to represent special characters or to control the formatting of the output.

Example: Escape Characters & Python Strings

Output:

Hello,
World!
Python  ProgrammingLanguage
Single Quote: ', Double Quote: "
Unicode: Ω
Beep!
Hex: Hello

Code Explanation:

  1. The provided code uses escape sequences to include special characters within strings.
  2. The first print statement uses the newline character escape sequence (\n) to move the cursor to the new line. This results in 'Hello' being printed in one line and 'World!' on the next line.
  3. The second print statement uses the new tab escape sequence (\t)  to create a tab space. The result is the creation of a tab space between the string. 
  4. The third print statement demonstrates the use of the single quote (\') and double-quote (\") escape sequences.  These help us insert single and double quotes within a string.
  5. The fourth print statement utilizes the Unicode character sequence \u03A9 to represent a Unicode character (Greek capital letter omega) in the output.
  6. The fifth print statement uses the escape character \a to produce a beep sound, though the audibility may vary depending on the environment.
  7. The sixth print statement demonstrates the use of the escape sequence \x48\x65\x6C\x6C\x6F, which represents the ASCII values for the characters forming the word "Hello" in hexadecimal.

Conclusion

A thorough understanding of Python strings is essential for any developer who wants to harness the full power of this amazing programming language. Strings serve as the bedrock for manipulating and representing textual data in Python programs. They offer a rich set of operations and methods that make it possible to conduct numerous operations and manipulation in string (i.e. texts).

Python's string capabilities cater to a wide range of programming needs, from basic operations like concatenation and repetition to advanced techniques such as string slicing, formatting, and utilizing escape characters. The simplicity and flexibility of string manipulation in Python contribute to the language's readability and ease of use. Remember, Python strings are not just characters; they are the building blocks of communication in your code.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

Frequently Asked Questions

Q. How to compare two strings in Python?

There are multiple ways in which you can compare strings in Python. These include the use of comparison operators like the equality (==) and inequality (!=) operators. While the inequality operator determines whether the strings are distinct, the equality operator determines whether they contain the same information.

Some other operators you can use are greater than (>), less than (<), less than equal to (<=), and greater than equal to (>=). These operators conduct lexicographic comparisons on two Python strings. Lastly, Python also has a built-in function called the str.compare() function, which is also used for comparing two strings. 

Q. What is the index() method in Python?

In Python, the index() method is a built-in function used with various data structures, including strings, lists, and tuples. This method is particularly associated with sequences, and it allows you to find the index (position) of a specified element within the sequence.

The basic syntax of the index() method is-

sequence.index(element[, start[, end]])

Here, 

  • sequence: The sequence of characters in which to find the element (e.g., a string, list, or tuple).
  • element: The element whose index you want to find.
  • start (optional): The index in the sequence where the search begins. If omitted, the search starts from the beginning.
  • end (optional): The index in the sequence where the search ends. If omitted, the search continues to the end of the sequence.

The index() method returns the index of the first occurrence of the specified element in the sequence. If the element is not found, it raises a ValueError.

Q. What does [:] mean in a Python array?

In Python, the [:] notation is used for slicing arrays, such as lists. This notation creates a copy of the entire array or a specified portion of it.

  • When applied to an array like original_array[:], it generates a new list that is a replica of the entire original array.
  • The [:] notation signifies that the entire range of elements is selected.
  • Alternatively, you can use slicing to copy a subset of the array by specifying start and end indices, like original_array[1:4], which creates a new list containing elements from index 1 to index 3 (excluding the element at index 4) of the original array.

Q. How to append strings in Python?

In Python, you can append strings using the concatenation operator (+) or by using the augmented assignment operator (+=). Both methods allow you to combine two or more strings into a new string. Below are the examples of both approaches.

Example Using Concatenation Operator (+):

In this example, the concatenate operator (+) is used to concatenate/ connect/ join the two strings along with a space in between. The result of the operation is stored in the appended_string variable.

Example Using Augmented Assignment Operator (+=):

In this example, the augmented operator (+=) is used for the augmented assignment. It is equivalent to string1 = string1 + " " + string2, and it appends the second string to the end of the first one. After this operation, the result is stored in string1, whose value will be Hello World.

Both methods are valid, but the choice between them depends on the specific context and coding style preferences. The augmented assignment operator can be more concise and efficient when appending multiple strings consecutively, as it modifies the existing string in place. However, for simple concatenation of two strings, the concatenate operator (+) is clear and straightforward.

Q. What are the functions of string?

Strings in Python are versatile and come with a variety of built-in functions and methods that facilitate the manipulation, analysis, and transformation of text data. Here are some key functions commonly used with Python strings:

  • len(): Returns the length of a string.
  • lower(): Converts a string to lowercase.
  • upper(): Converts a string to uppercase.
  • strip(): Removes leading and trailing whitespace from a string.
  • split(): Splits a string into a list of substrings based on a specified delimiter.
  • join(): Concatenates a list of strings into a single string, using a specified separator.
  • replace(): Replaces occurrences of a specified substring with another substring.
  • find(): Searches for a substring within a string and returns its index.
  • startswith(): Checks if a string starts with a specified prefix.
  • endswith(): Checks if a string ends with a specified suffix.

Q. Are strings the same as arrays in Python?

In Python, strings can be considered arrays of characters, where each character in the string is associated with a specific position, or index, within the array. This characteristic allows Python strings to be treated and manipulated using array-like operations, such as accessing individual characters by their index, iterating over the characters, and performing slicing to extract substrings.

However, it's essential to note that Python strings are immutable, which means once a string is created, its individual characters cannot be changed directly. Instead, any operation that appears to modify the string results in a new string being created.

Example:

Output:

y

Code Explanation:

  1. We define a variable a and assign the string value 'Python strings!' to it.
  2. Next, we access an element of the string using the indexes. Here, the expression a[1] is used to access the single character at index 1.
  3. In Python, indexing starts at 0, so the person at index 1 is the second character in the string.
  4. The expression is placed inside the print() function, which subsequently displays the character at the second position in the Python string, to the console.

You might also be interested in reading the following:

  1. Learn Python for Data Science in 4 Easy Steps
  2. Advantages and Disadvantages of Python
  3. Difference Between C and Python | C or Python - Which One Is Better?
  4. 20+ Best Python Projects Ideas
  5. Best Python Books For Beginners, Intermediates And Experts
Edited by
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

Tags:
Computer Science Engineering

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.