Python Strings


A string is a sequence or a collection of characters enclosed within single or double-quotes. In Python, the print() function is used to display a string.

Since a computer understands only 0 and 1 i.e. binary numbers. First, it converts characters into binary numbers and then performs required operations, this process is known as character encoding. Similarly, the process to convert a string from binary to its original form is known as character decoding.

There are several encoding schemes for example ASCII, Unicode. Python uses Unicode characters for the string.

Examples of string in Python

The given are the examples of string in Python –

# Example of the string enclosed within single quotes in Python
print('Hello World!')
# Example of Python string enclosed within double quotes
print("Hello World!")

Multiline string

A multiline string in Python is the text which is split across multiple lines and enclosed within the triple quotes.

# Example of a multiline string in Python

print(''' But I must explain to you how all this mistaken idea of
denouncing pleasure and praising pain was born and I will give
you a complete account of the system, and expound the actual
teachings of the great explorer of the truth, the master-builder
of human happiness.''')

Assigning a string to a variable

You can directly assign a single line or multiline string to a variable example of which is given below.

s="Hello World!"
print(s)

You can see the output of this code in the given image –

Accessing characters of a string by index

We can access each character of a string by using indices. Since Python doesn’t have character datatype each character is a substring of the string. Python allows negative indexing that means -1 refers to the last item similarly -2 refers second-last item and so on.

For example –

s="HELLO"
print(s[0])
print(s[4])
print(s[-1])
print(s[-2])

On executing this code you will see the given output. Here 4 and -1 will refer to the same character.

String operations

There are many operations that can be performed on one or more strings. We will discuss all of them one by one.

String concatenation

Joining two or more strings into a single string is called string concatenation. In Python + operator is used for concatenating two strings.

For example –

s1="Hello"
s2="World!"
s3=s1+s2
print(s3)

This will join Hello and World! and print it on standard output.

String slicing

String slicing is to obtaining a substring from a string that means we can extract a range of characters from a string with string slicing. You can mention the start and end index which is separated by a colon, of a substring that you want to slice.

For example-

s= "Python Programming"
print (s[2:8])

This will slice the highlighted part of the string Python Programming. The character at index 8 will be excluded now see the output of this program.

Similarly, you can use negative indices to slice a string.

For example –

print (s[-7:-3])

this will print ramm the character at the index -3 will be excluded.

Please note index should be of type integer otherwise it will through TypeError. Another error IndexError will arise when you use out of range index.

Format a string in Python

There are multiple ways to format strings in Python.

String formating with format() method

Python provides format() method for formatting strings. Curly braces within a string are used as the replacement filed that gets replaced with a certain value.

For example –

a=10
b=20
c=a+b
str="The sum of two numbers is {}"
print(str.format(c))

You can see the output in the given image –

You can specify multiple arguments separated with a comma. The format() method can take unlimited arguments. You can see this in the example below.

a=10
b=20
c=a+b
d=a*b
str="The sum of a and b is {} and product is {}"
print(str.format(c,d))

f-string: a new approach of string formatting (3.6+)

In Python 3.6 a new feature was added which is known as a formatted string literal or f-string. It provides a new approach to format a string in Python. We prefix the string with f and values are given inside the curly braces.

See the example below –

a=10
b=20
c=a+b
d=a*b
print(f"The sum of a and b is {c} and product is {d}")

You can see the output in the given image –

Python string methods

Python provides some built-in methods that can be used with strings. For example, upper() and lower() methods can be used to convert characters of a string to uppercase and lowercase respectively.

For example –

s1="hello"
s2="WORLD"
print(s1.upper())
print(s2.lower())

This program will convert characters of string s1 to uppercase and string s2 to lowercase. You can see this in the image below.

Similarly, you can remove whitespaces that are at the beginning or end of the actual text using the strip() method.

For example –

s =" Hello World ! "
print(s.strip())

You can see the output in the given image –

There are so many other useful methods that can be used on strings in Python. You can find a detailed list of string methods in Python’s official documentation.

Conclusion

Ok, that’s all for now. Learn and start practicing on your own, if find any difficulty then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.