Strings in Python

Amit Dhanwani on March 28, 2024

Strings in Python

An introduction to Strings in Python


 

Strings in Python are essentially just collections of characters kept in variables for different purposes in the majority of computer languages.

Python strings are no different and provide several advantages, including the ability to generate messages for users to enhance their user interface. Both the Python language and the topic of Python strings are extremely robust.

Beyond that, strings may be used to provide methods for tracking and managing the behavior of the computer program itself. They are also commonly utilized to support testing and debugging duties and aid in the further development of your product.

In Python, a string is a type of data structure that holds a string of characters. Since it is an immutable data type, you are unable to alter a string after you have generated it. Strings are extensively utilized in a broad range of applications, including the storage and manipulation of text data as well as the representation of names, addresses, and other text-representable data types.

Single quotes are used for regular expressions, dict keys; double quotes are used for string representation. Therefore, in Python, both single quotes and double quotes represent strings; yet, there are situations when we must employ one type over the other.

In Python, a single character is just a string with a length of 1. The language provides a character data type.

Example:

‘Codingal’ or “codingal” or ‘a’ or “a”

print("Codingal is fun")
print('Codingal')

Output:

Codingal is fun

'Codingal'

 

Creation of string in python:


 

Python allows the creation of strings using single, double, or even triple quotes. Now let’s look at how to define a string in Python.

Example:

# Python Program for Creation of String
# Creating a String with single Quotes
String1 = 'Codingal is on a mission to inspire school kids to fall in love with coding.'
print("String with the use of Single Quotes: ")
print(String1)
 
# Creating a String with double Quotes
String1 = "Coding is proven to develop creativity, logical thinking and problem solving skills in kids."
print("\nString with the use of Double Quotes: ")
print(String1)
 
# Creating a String with triple Quotes
String1 = '''To build the largest online platform to provide computer science education to K-12 students"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
 
# Creating String with triple Quotes allows multiple lines
String1 = '''Students
Love
Codingal'''
 
print("\nCreating a multiline String: ")
print(String1)

Output:

String with the use of Single Quotes:

Codingal is on a mission to inspire school kids to fall in love with coding.

 

String with the use of Double Quotes:

Coding is proven to develop creativity, logical thinking and problem solving skills in kids.

 

String with the use of Triple Quotes:

To build the largest online platform to provide computer science education to K-12 students"

Creating a multiline String:

Students

 

Character access in a Python string:


 

In Python, the Indexing method can be used to get specific characters from a String.

In a Python string, every character has an index, which must be an integer and begins at 0.

Positive and negative integers can be used to access the characters in two different ways.

Negative address references, such as -1 for the very last character, -2 for the second last character, and so on, can access characters from the back of the String because of indexing.

The slicing operator (:) may be used to retrieve a range of objects from a string.

To further understand how the positive and negative indexes function in a Python string, consider the following example:

 

Positive Indexing01234567
CODINGAL
Negative Indexing-8-7-6-5-4-3-2-1

Figure 1: Indexing of python string “CODINGAL”.

 

Example 1:

In this example, we will build a string “CODINGAL” in Python and use both positive and negative indexing to retrieve its characters. The string’s initial character will be the 0th element, and its last character will be the -1th element.

s = 'CODINGAL'
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
print(s[6])
print(s[7])

Output:

C

O

D

I

N

G

A

L

 

We must utilize negative numbers in the following manner in order to obtain the identical result in reverse order.

 

Example 2:

s = 'CODINGAL'
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
print(s[-6])
print(s[-7])
print(s[-8])

Output:

L

A

G

N

I

D

O

C

 

Iterating Through Strings:


 

We can also use loops to iterate over the characters within a string. Doing this gives you the ability to interact with the individual characters.

Example:

# Iterating over a string
a="CODINGAL"
for i in a:
   print (i)

Output:

C

O

D

I

N

G

A

L

 

Checking Sub-string:


 

Substring checks and string membership checks are two common terms used to describe searching for a string inside another string.

To locate the target string, these checks iteratively search behind the scenes.

This is helpful as it eliminates the need for you to manually iterate over the string.

We may save time and maintain the organization and cleanliness of our code by carrying out membership tests.

This will return True if match is found else it will return False.

Example:

a = 'I' in 'CODINGAL'
print(a)

Output:

True

 

It is important to note that case matters in this kind of membership verification. Only when a letter is discovered in uppercase will a search for it in capital letters provide a correct result.

Example:

a = 'i' in 'CODINGAL'
print(a)

Output:

False

 

Concatenating Strings:


 

The practice of joining two or more strings or characters to form new strings is known as concatenation.

Strings cannot have their values changed since they are immutable, but they may be overwritten; string concatenation is a popular method for doing this operation.

This is a low-level recursive pattern that may be used to create personalized messages for users as well as update strings with new values.

Additionally, real-time concatenation is possible. For example, concatenating while a call to the print function is being made.

Example:

a="CODINGAL"
b="Loves"
c="STUDENTS"
print(c +" " +b + " " +a + " ")

Output:

STUDENTS Loves CODINGAL

 

These code blocks demonstrate legitimate methods for joining strings together, and we can accomplish a lot with user messages, notes, comments, and much more by using string concatenation.

 

String Slicing:


 

The String Slicing function in Python may be used to retrieve a range of characters from the String.

To slice anything in a string, use a slicing operator, such as a colon (:).

When utilizing this technique, keep in mind that the character at the start index is included in the string that is returned, but the character at the last index is not.

In the following example, we will extract a substring from the original string using the string-slicing technique.

The string slicing will begin at the string’s 2nd index and continue to the 6th index, with the sixth character excluded, as indicated by the [2:6].

Negative indexing is an additional method of string slicing.

 

Example:

# Python Program to demonstrate String slicing
# Creating a String
String1 = "CODINGAL"
print("Initial String: ")
print(String1)
 
# Printing 2nd to 6th character
print("\nSlicing characters from 2-6: ")
print(String1[2:6])
 
# Printing characters between 3rd and 2nd last character
print("\nSlicing characters between " + "3rd and 2nd last character: ")
print(String1[3:-1])

Output:

Initial String:

CODINGAL

 

Initial String:

CODINGAL

 

Slicing characters between 3rd and 2nd last character:

INGA

 

Reversing a String in Python:


 

Python allows us to reverse strings by accessing characters from a string. By employing the string slicing approach, we may reverse a string.

In the example that follows, we will use the index to reverse a string. Since we are taking into account the entire string, from the start index to the end index, we did not mention the first two sections of the slice.

Example 1:

#Program to reverse a string
a = "CODINGAL"
print(a[::-1])

Output:

LAGNIDOC

 

Using the built-in join and reversed functions, as well as giving the string as an argument to the reversed() method, we can also reverse a string.

 

Example 2:

# Program to reverse a string
a = "CODINGAL"
 
# Reverse the string using reversed and join function
ab = "".join(reversed(a))
 
print(ab)

Ouput:

LAGNIDOC

 

Updating a character:


 

To update a character in a Python string, first convert the string to a Python List, and then update the list element.

We can change the character and then convert the list back into the String because lists are mutable by nature.

Using the string slicing approach is an additional technique.

Before updating a character, slice the string, add the new character, and then slice the remaining portion of the string once again.

The following example updates a character by utilizing both the list and the string slicing mechanism. Using the Python string join() function, we first transformed the String1 to a list, changed its value at a certain element, and then returned the list back to a string.

Using the string-slicing approach, we first cut the string to the desired character, concatenate it, and then concatenate the remaining portion of the string.

Example:

# Python Program to Update character of a String
String1 = "Codingal is best place to learn coding"
print("Original String: ")
print(String1)
 
# Updating a character of the String
# As python strings are immutable, they don't support item updating directly there are following two ways
 
#1
list1 = list(String1)
list1[11] = ' the '
String2 = ''.join(list1) print("\nUpdating character at 11th Index: ")
print(String2)
 
#2
String3 = String1[0:11] + ' the ' + String1[12:]
print(String3)

Output:

Original String:

Codingal is best place to learn coding

 

Updating character at 11th Index:

Codingal is the best place to learn coding

Codingal is the best place to learn coding

 

Updating Entire String:


 

Python strings are immutable by nature, therefore we are unable to change an existing string. The variable that has the same name can only have a whole new value assigned to it.

In the following example, we assign a value to “String1” first, and then we update it with a value that is entirely different. All we did was modify its reference.

Example:

# Python Program to Update entire String.
String1 = "Hello Guys"
print("Original String: ")
print(String1)
 
# Updating a String
String1 = "Hi Students, Welcome to Codingal"
print("\nUpdated String: ")
print(String1)

Output:

Original String:

Hello Guys

 

Updated String:

Hi Students, Welcome to Codingal

 

Deleting a character:


 

Since Python strings are immutable, we are unable to remove a character from them. The del keyword will produce an error if we try to delete the character.

Example 1:

# Python Program to delete character of a String
String1 = "Hello guys"
print("Original String: ")
print(String1)
 
print("Deleting character at 4th Index:")
del String1[4]
print(String1)

Output:

Original String:

Hello guys

Deleting character at 4th Index:

ERROR!

Traceback (most recent call last):

File "<string>", line 8, in <module>

TypeError: 'str' object doesn't support item deletion

 

However, we can extract the character from the original string and save the result in a new string by using slicing.

 

Example 2:

In this case, we will first slice the string up to the character we wish to delete and then we will concatenate the string that remains after the removal of the character.

In this example, in the original string “Helllo Guys, Welcome to Codingal”, ‘l’ is entered extra at position 2, we are going to delete that by following this method

 

# Python Program to delete characters from a String
String1 = "Helllo Guys, Welcome to Codingal"
print("Original String: ")
print(String1)
 
# Deleting a character of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)

Output:

Original String:

Helllo Guys, Welcome to Codingal

 

Deleting character at 2nd Index:

Hello Guys, Welcome to Codingal

 

Deleting a character:


 

The del keyword allows for the complete string to be deleted. Additionally, the string has been erased and cannot be printed, therefore trying to print it will result in an error.

 

Example:

# Python Program to delete entire String
String1 = "Hello Guys, Welcome to Codingal"
print("Original String: ")
print(String1)
 
 
# Deleting a String with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Output:

Original String:

Hello Guys, Welcome to Codingal

 

Deleting entire String:

Traceback (most recent call last):

File "<string>", line 10, in <module>

ERROR!

NameError: name 'String1' is not defined

 

Formatting of Strings:


 

The format() function, a very flexible and strong tool for formatting Strings, may be used to format Strings in Python.

Curly braces {} are placeholders in the String format method that can hold arguments based on position or keyword to specify order.

Example 1:

To demonstrate how string declaration position matters, we will declare a string in this example that has the curly braces {}, which serve as placeholders. We will then supply values for them.

# Python Program for formatting of Strings
# Default order
String1 = "{} {} {}".format('Codingal', 'is', 'Love')
print("Print String in default order: ")
print(String1)
 
# Positional Formatting
String1 = "{2} {1} {0}".format('Codingal', 'is', 'Love')
print("\nPrint String in Positional order: ")
print(String1)
 
# Keyword Formatting
String1 = "{a} {b} {c}".format(a='Codingal', b='is', c='Love')
print("\nPrint String in order of Keywords: ")
print(String1)

Output:

print("\nPrint String in order of Keywords: ")

print(String1)

 

Print String in Positional order:

Love is Codingal

 

Print String in order of Keywords:

Codingal is Love

 

Format Specifiers in Strings:


 

In strings, format specifiers are used to align a string left, right, or center; they are separated by a colon(:).

The alignment of a string is indicated by the characters (<), (>), and (^), which indicate left, right, and center alignment, respectively.

The length in which it should be aligned is another option.

For instance, the string should be aligned to the left within a field with a width of 9 characters if (<9) is used.

 

Example:

# String alignment
String1 = "|{:<8}|{:^2}|{:>1}|".format('Codingal', 'is', 'Love')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
 
# To demonstrate aligning of spaces
String1 = "\n{0:^3} is on a mission to inspire school kids to fall in love with {0:<2}".format("Codingal", "Coding")
print(String1)

Output:

Left, center and right alignment with Formatting:

|Codingal|is|Love|

 

Codingal is on a mission to inspire school kids to fall in love with Codingal

 

Conclusion:


A vital part of using Python is the Python String. There is much more to Python strings than what was discussed in this article, even if it did cover some of the fundamentals, including several Python string functions. For a newbie, Python is a somewhat approachable language.

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class