Strings in Python

Introduction

A string is a sequence of characters and is considered a data type. It can also contain spaces, numbers, special characters, etc. In this tutorial, you will learn how to deal with strings in python. We will go through several examples here to cover every single piece of information related to this topic.

Let's see an example of a string.

"Welcome to PySeek"

Concatenate Two Strings in Python

In python, you can concatenate multiple strings easily by using the plus(+) sign. Below is an example for you.


f_name="Subhankar"
l_name="Rakshit"
print("Full Name:- ", f_name + " " + l_name)

# Another example
os_name = "Kali Linux"
print(os_name + " 3.7")
print(os_name + str(3.7))

Output

Full Name:-  Subhankar Rakshit

Kali Linux 3.7
Kali Linux3.7

Multi-line String

Suppose you want to print a long text through a python program. The text consists of many lines. So, how do you manage to fit the entire text on the screen in a compact format?

We can do it simply by entering the text between triple quotations ("""text here"""). See the example below.


multi_line = """Every operating system has a host file called
'hosts' locates in a fixed path depending on the
operating system. It's a simple text file, maps
hostnames to IP addresses. It contains the names of
several hosts, including their respective IP addresses."""

print(multi_line)

Output

Every operating system has a host file called
'hosts' locates in a fixed path depending on the
operating system. It's a simple text file, maps
hostnames to IP addresses. It contains the names of
several hosts, including their respective IP addresses.
Linux is an Open Source operating system
Linux is an Open Source operating system

String Formatting in Python

format() method

For example, if you want to print the content of a variable in a string but not the variable name, how do you do that? There is a  method called format() that helps to concatenate elements within a string through the positional place. It's a string formatting feature in python3 and above.


type = "Open Source"
os_name = "Linux"

print("{} is an {} operating system".format(os_name, type))

Output

Linux is an Open Source operating system

f-strings

It is the latest feature of python strings which is added to python3.6 and the higher version. It's the easiest way for string formatting. It also does the same task we did just in the previous example. Here, you just need to put the letter 'f' at the beginning of the string.

Code


os_name = "Linux"
type = "Open Source"

print(f"{os_name} is an {type} operating system")

Output

Linux is an Open Source operating system

String Indexing

Indexing helps to access any individual characters in a string using positional value. Zero(0) is the first positional value of any string. 

See the example below. You will find many examples of different string indexing. I have added a single comment line before each line of the code. I hope you will grab the objectives easily once you see them.


name="Subhankar"
print(name[0])
# The last character
print(name[-1])
# 0 to end
print(name[0:])
# Reverse order.
# [start:end:step]
print(name[-1::-1])
# Another method for reverse printing
print(name[::-1])

# Method 1: Incrementing the index of the string by 2
print(name[0::2])
# Method 2: Incrementing the index of the string by 2
print("Anonymous"[0::2])

Output

S
r
Subhankar
raknahbuS
raknahbuS
Sbakr
Aoyos

String Methods in Python

Python provides many string methods that allow users to perform different operations with strings.

Basic Methods

There are some basic methods you need to know. 

Examples -

len(): Find the length of a string

lower(): It is used to lowercase all the characters in a string.

upper(): It's used to uppercase all the characters in a string.

title(): It formats a string into title format. For example, if a normal string looks like "welcome to pyseek", the title formatting will look like "Welcome To Pyseek".

count(): It helps to find the number of occurrences of a specified character.

The code below is the programming implementation of the methods mentioned above.


string = "welcome to PySeek"
print("The length of the string is: ",len(string))
print("Lower: ", string.lower())
print("Upper: ", string.upper())
print("Title: ", string.title())
print("The number of \"s\" is: ", string.lower().count("s"))

Output

The length of the string is:  17
Lower:  welcome to pyseek
Upper:  WELCOME TO PYSEEK
Title:  Welcome To Pyseek
The number of "s" is:  1

strip() Method

The strip() method is a built-in function in python used for removing spaces from the left and right position of the string based on the argument passed into the function.

strip(): It removes spaces from both sides, left and right.

lstrip(): It removes spaces only from the left side.

rstrip(): It only removes spaces from the right side.


name=" Subhankar "
dots=".........."

print("1.", name + dots)
# Remove all the spaces from the left
print("2.", name.lstrip()+dots)
# Remove all the spaces from the right
print("3.", name.rstrip()+dots)
# Remove all the spaces from the both side
print("4.", name.strip()+dots)

Output

1.       Subhankar         ..........
2. Subhankar         ..........
3.       Subhankar..........
4. Subhankar..........

replace() Method in Python

replace() method is used to replace all the specified sub-string with other specified sub-string.

Syntax

replace('being replace', 'replace with')


string1 = "I Love Python"
# Replace all the spaces with an underscore
print(string1.replace(" ","_"))
# Another example
string2 = "I Love Python"
# Replace the word: 'Love' with 'Hate'
print(string2.replace("Love", "Hate"))

Output

I_Love_Python
I Hate Python

The find() method

find method is a built-in function in python that finds the first occurrence of a given text passed as an argument into the function.

Syntax

find('search value', 'starting position', 'ending position')

starting position: Optional. By default, starts from 0.

ending position: Optional. By default, the end of the string.


string = """Python is a programming language.
It is very easy to learn"""
# It will print the first occurrence position of the
# string: 'is'
print(string.find("is"))

occur = string.find("is")
# It will print the next occurrence of 'is'
print(string.find("is", occur+1))

Output

7
38

center() Method in Python

The center() method helps to align a string in the middle padded with specified characters on both sides.

Syntax

center(length, character)

length: length of the string + extra spaces for both sides as you need.

character: Optional, by default it uses SPACE.

See the example below for a better understanding.


name = "Subhankar"
length = len(name)
# length of 'Subhankar' + 10 more spaces
print(name.center(length+10,"*"))

Output

*****Subhankar*****

Summary

In this tutorial, you learned what strings actually are, how to operate strings in python, and several methods which are used to perform various operations with strings.

We covered many examples here to know this topic better. If you have any doubt, let me know in the comment section. You will get an immediate response.

That's all for today. Have a nice day ahead, cheers!

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post