Exploring Strings in Python: A Simple Guide

Sagar SahuSagar Sahu
8 min read

Jr. Coder:
Hello, Jr. Coder Is everything crystal clear in your Python journey?

Dadu:
Yes, Dadu But I have a doubt about strings.
What is a string?
How do we use it in a program?
Do strings have any extra features?
Huhhh... Dadu, please help me naaa!

Dadu:
Okay, calm down, beta. Don’t worry when your Grandpa is here!
Let’s start with the basics:

What is a string?
In Python, anything enclosed within single (' ') or double (" ") quotation marks is called a string.
We can display strings using the print() function.

print("Hello, Jr. Coder!")
print('Welcome to the Python world!')

if you want to wright a multi-line string you can use triple quotes ( ‘ ‘ ‘ or “ “ “ )

print("""This is a
multi-line string
in Python.""")

We can access chharacters from the string using indexing due to string in Python are sequences of character. Strings are indexed starting from 0 and -1 from ends. this allw us to retrieve specific characters from the string.

slicing and indexing in python

Strings in Python are immutable. This means that they cannot be changed after they are created. I think you know about mutable and immutable in Python. If not, don't worry, Grandpa has a guide for you

mutable and immutable

Have you seen your grandma's masala dabba? Once it is filled with a specific masala, it cannot hold another type until the dabba is completely emptied or cleaned. This is known as immutability, meaning once a variable is created with a specific value, it cannot be changed until it is entirely removed from memory. In contrast, with mutability, a variable's value can be changed after it is created.

mutable: Here an object can be changed afterward it created in a program like list, set, dictionary

immutable Objects are of in-built data type like int , float, bool, string, Unicode, and tiple in simple words, an immutable object can’t be changed after it is created.

Raju’s grinning, bursting with excitement to dive into data types and operators! So, let’s get started with a sip of green tea.

incase if we need to manipulte strings then we can use methos like

#concatenation #slicing #formating

# Concatenation
first_name = "Raju"
last_name = "Sahu"
full_name = first_name + " " + last_name
print("Concatenation:", full_name)  # Output: Raju Sahu

# Slicing
sliced = full_name[0:4]  # Get characters from index 0 to 3
print("Slicing:", sliced)  # Output: Raju

# Formatting
age = 30
formatted_string = f"My name is {full_name} and I am {age} years old."
print("Formatting:", formatted_string)
# Output: My name is Sagar Sahu and I am 21 years old.

We can repeat a string multiple times using \ Operator*

s = "Hello "
print(s * 3) #output>>> Hello Hello Hello

In Python, it is not possible to delete individual characters from a string since strings are immutable. However, we can delete an entire string variable using the del keyword.

name = "sagar sahu"
print(name) # print = sagar sahu
del name  # delet the entire string
name = "tinu "
print(name) # print = tinu

But if we need to modify a part of string we use “ + “ with slicing or replace( )

NOTE: Since a string is an immutable type, we cannot change a character or replace it with another string; we just create a new string for modifying or replacing.

s = "hello g"

# Updating by creating a new string
s1 = "H" + s[1:]

# replacnig "g" with "Raju"
s2 = s.replace("g", "Raju")
print(s1) # output>> Hello Raju    
print(s2) #

We have a built-in method to check the total length of the string len( )

name = " Raju"
print(len(name))
#output>> 4

upper( ) and lower( ): upper ( ) is used to convert all character to upper case while lower( ) is used to convert all character to lowercase

name =  "SAGAR SAHU"
print(name.lower()) # output>> sagar sahu

print(name.upper()) # output>> SAGAR SAHU

Capitalize( ) is used in python where the first letter of the string is converted into uppercase and the rest of the characters remain the same

first_name = "SAGAR"

second_name = "raju"

capitalized_string = first_name.capitalize()
print("first_name =>" cpitalized_string)  # output>> Sagar
capitalized_string = second_name.capitaalize()
print("second_name => " capitalize_string) # output >>> Raju

join( ) :- the join( ) is used in python programing to merge each element of an iterable such as a list,set.etc. and leter we can use a string separator to separate the value. thus.

text = ['Anshul', 'is', 'my', 'only', 'friend']

# join elements of text with space
print(' '.join(text)) #output Anshul is my only friend

Formatting f-string

name = "Raju"
age = 21
print(f"Name: {name}, Age: {age}") #output>> Name: Raju, Age:21

count( ):- to count the number of occurance of an individual element or substring that appear within the string. it throw the numeric value that provides the detail of an actual count of a given string

Count_H = "hellohhollohollo"
print("number of occurance of h:",count_H.count("h")) # number of occurance of h: 4

find( ):- return the lowest index value from the first occurrence of a string (only in case if its found): else the value would be -1

message = 'Yuvraj is my name'

# check the index of 'is'
print(message.find('is')) #output>> 7

replace( ):-any unwanted character or text and replace it with the new desired output within the string. The replace() can be used in Python with the below-mentioned syntax to perform the action:

text = 'subway surfer'

# replace s with t
replaced_text = text.replace('s', 't')
print(replaced_text) #output>> tubway turfer

Tabulation of all methods in string » these are not only for strings; they are also applicable for lists, tuples, sets, etc.

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isascii()Returns True if all characters in the string are ascii characters
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Converts the elements of an iterable into a string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list
0
Subscribe to my newsletter

Read articles from Sagar Sahu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sagar Sahu
Sagar Sahu