Python Strings and Its Implementation

By Shubham Singh Rajawat Last updated : November 29, 2023

Python Strings

Python strings are immutable means they cannot be changed once defined.

In Python, strings can be directly used within either single quotation marks ('Hello World' or double quotation marks "Hello World".

The print() method can be used to print the value of a string.

Assign Strings

Use a variable and assign the string value (surrounded by single quotation marks ' ', or double quotation marks " ") directly using the equal (=) sign.

Example

In this example, we are declaring two variables, assigning strings to them, and then printing their values.

# Declaring variables and assigning strings
name = "Alvin Alex"
city = "New York, USA"
 
# Printing the variables
print("Hello, my name is " + name + " I live in " + city + ".")

The output of the above example is:

Hello, my name is Alvin Alex I live in New York, USA.

Assign Multiline String

The multiline string can be assigned using the three quotes ("""). Start the assignment with a set of three quotes and then write your multiple string and then end the assignment with a set of three quotes (""").

Example

In this example, we are declaring a variable, assigning multilne string, and printing it.

# Declaring variable and assign multline string
text = """My name is Alvin.
I lives in New Yourk City.
I am 32 years old. My hobbies are
playing cricket, badminton and table tennis.
"""
print("The value of text is:\n", text)

The output of the above example is:

The value of text is:
 My name is Alvin.
I lives in New Yourk City.
I am 32 years old. My hobbies are
playing cricket, badminton and table tennis.

Getting String Length

String length is the total number of characters, use the len() method to get the length of the string. The len() is a built-in method of the Python standard library.

Example

In this example, we are declaring two string variables, getting and printing their lengths.

# Deaclre strings
string1 = "Hello, world!"
string2 = "Hey, how are you?"
 
# Finding length
length1 = len(string1)
length2 = len(string2)
 
# Printing length
print("Length of", string1, "is", length1)
print("Length of", string2, "is", length2)

The output of the above example is:

Length of Hello, world! is 13
Length of Hey, how are you? is 17

Accessing String

Strings are arrays and just like an array, we can access string by using the index inside the square brackets [] which starts from 0 to string length -1.

Example

In this example, we are declaring a string, and accessing its characters.

# Declaring a string
my_string = "Hello, World!"
 
# Accessing and printing characters
print("The first character is:", my_string[0])
print("The second character is:", my_string[1])
print("The third character is:", my_string[2])
print("The last character is:", my_string[-1])

The output of the above example is:

The first character is: H
The second character is: e
The third character is: l
The last character is: !

String Slicing

String slicing means accessing a substring from the given string, this can be done by using a simple syntax.

string_name[beg:end:step]

Here,

  • beg : is the beginning index
  • end : is the end index but end is not inclusive
  • step : distance between every word (steps are optional)

Note! If step is given -1 means a reverse string is returned.

Example

In this example, we are implementing string slicing.

string="includehelp is a portal to learn concepts"
print(string[3:7])
print(string[:7])
print(string[15:])
print(string[0::3])
print(string[7:3:-1])
print(string[::-1])

The output of the above example is:

lude
include
a portal to learn concepts
ileliaoatlrcct
hedu
stpecnoc nrael ot latrop a si plehedulcni

Iterating String

You can iterate over characters of a string in Python using the for loop.

Example

Python program to iterate over characters of a string.

# Declaring a string
my_string = "Hello, World!"
 
# Iterating over characters of a string
for c in my_string:
    print(c, end="")

The output of the above example is:

Hello, World!

Note: In the above example, we used the end parameter to ignore the printing of a new line after each character.

Check Substring in String

To check substring in a string, you can use the if condition with in operator.

Example

# Declaring a string
my_string = "Hello, World!"

# Checking substring in string
if "Hello" in my_string:
    print('Yes, "Hello" is there')
else:
    print('No, "Hello" is not there')

if "hey" in my_string:
    print('Yes, "hey" is there')
else:
    print('No, "hey" is not there')

The output of the above example is:

Yes, "Hello" is there
No, "hey" is not there

Check String Immutability

To check whether strings are immutable in nature or not, try to its change one of the characters.

Example

Python program to show that strings are immutable.

string ="include"
string[5]="i"

The output of the above example is:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    string[5]="i"
TypeError: 'str' object does not support item assignment

This proves that python for badges to change a pre defined string but we can do one thing we can reassign its value.

String Variable Type

The type of a string variable is <class 'str'>. To get the type of a string, you can simply use the type() method.

Example

In this example, we are getting and print the type of the string variables.

# Declaring a string
my_string = "Hello, World!"

# Getting type of the string
print("my_string is of type: ", type(my_string))

The output of the above example is:

my_string is of type:  <class 'str'>

Update Strings

In Python, strings are immutable, so we cannot update the string. We can update the entire string i.e., we can change the value of the string variable by assigning the new one.

Example

In this example, we are updating the entire string to the string variable.

# Declaring a string
my_string = "Hello, World!"

# Printing the value
print("my_string: ", my_string)

# Updating string
my_string = "Welcome at IncludeHelp"

# Printing the value after updating
print("my_string (after update): ", my_string)

The output of the above example is:

my_string:  Hello, World!
my_string (after update):  Welcome at IncludeHelp

Delete a Character

Deleting a character means updating a string which is not possible with Python strings because strings are immutable. If we try to delete a character from the string, it will generate a TypeError: 'string_object_name' object does not support item deletion.

Example

In this example, we are trying to delete a character from the string.

# Declaring a string
my_string = "Hello, World!"
 
# Printing the value
print("my_string: ", my_string)
 
# deleting a char from a string
del my_string[0]
 
# Printing the updated vlaue
print("my_string (after update): ", my_string)

The output of the above example is:

my_string:  Hello, World!
Traceback (most recent call last):
  File "/home/main.py", line 8, in <module>
    del my_string[0]
TypeError: 'str' object doesn't support item deletion

Delete String

Deletion of the entire string is possible with the del keyword. Once the string object is deleted, you cannot access it again. For example, if you try to print the string object, it will generate a NameError: name 'string_object_name' is not defined.

Example

In this example, we are deleting the entire string i.e., deleting a string object and we are trying to access it again.

# Declaring a string
my_string = "Hello, World!"

# Printing the value
print("my_string: ", my_string)

# Deleting the entire string
del my_string

# Trying to print my_string
print("my_string: ", my_string)

The output of the above example is:

my_string:  Hello, World!
Traceback (most recent call last):
  File "/home/main.py", line 11, in <module>
    print("my_string: ", my_string)
NameError: name 'my_string' is not defined

Revere String

By using the string slicing you can access the elements from the last and by using this way, a string can be reversed. Use string_object[::-1] to reverse a string.

Example

In this example, we are reversing a string using the string slicing.

# Declaring a string
my_string = "Hello, World!"

# Printing the value
print("my_string: ", my_string)

# Reversing the string
reverse_string = my_string[::-1]

# Printing the reverse string
print("reverse_string: ", reverse_string)

The output of the above example is:

my_string:  Hello, World!
reverse_string:  !dlroW ,olleH

Concatenate Strings

To concatenate two or more strings, use the plus (+) operator. It will return the concatenated string.

Example

In this example, we are concatenating two or more strings.

# Declaring two strings
str1 = "Hello, World!"
str2 = "How're you?"

# Concatenating strings
result = str1 + " " + str2

# Printing strings
print("str1:", str1)
print("str2:", str2)
print("Concatenate string (result):", result)

The output of the above example is:

str1: Hello, World!
str2: How're you?
Concatenate string (result): Hello, World! How're you?

Formatting String

Formatting strings means combining other types with the string, you can use the .format() method with the placeholder {} to format a string. The .format() method takes the argument(s), formats them, and places the formatted value at the place of placeholder inside the string.

Example

In this example, we are formatting the string with the given values (age and height).

# Declaring two strings
age = 21
height = 167

# Formatting string
result = "My age is {} and my height is {} cm.".format(age, height)

# Printing result
print("Formatted string (result):", result)

# More examples

# The default order
result = "{} {} {}".format("Alex", age, height)
print("result:", result)

# The positional order (indexes in placeholders)
result = "{0} {1} {2}".format("Alex", age, height)
print("result:", result)

# Using keywords in placeholders
result = "{na} {ag} {hg}".format(na="Alex", ag=age, hg=height)
print("result:", result)

The output of the above example is:

Formatted string (result): My age is 21 and my height is 167 cm.
result: Alex 21 167
result: Alex 21 167
result: Alex 21 167

Python String Addition Resources

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.