Day #13 - String Methods in Python

Day #13 - String Methods in Python

ยท

6 min read

Introduction

Welcome to day 13 of my python coding journey blog post. On day 13, I learnt about different methods of strings in python. Python provides various built-in string methods that can be used to alter and modify the strings. Let's dive deep into the details.

So let's get started......

Methods of Strings in python

upper(): The upper() method converts a string to upper case.

str1 = "AbcDEfghIJ"
print(str1.upper())
ABCDEFGHIJ

lower(): The lower() method converts a string to lowercase.

str1 = "AbcDEfghIJ"
print(str1.lower())
abcdefghij

strip(): The strip() method removes any white spaces before and after the string.

str2 = " Silver Spoon "
print(str2.strip)
Silver Spoon

rstrip(): The rstrip() removes any trailing characters. Example:

str3 = "Hello !!!"
print(str3.rstrip("!"))
Hello

replace(): The replace() method replaces all occurrences of a string with another string. Example:

str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))
Silver Moon

split(): The split() method splits the given string at the specified instance and returns the separated strings as list items.

str2 = "Silver Spoon"
print(str2.split(" "))      #Splits the string at the whitespace " ".
['Silver', 'Spoon']

capitalize(): The capitalize() method turns only the first character of the string to uppercase and the rest other characters of the string are turned to lowercase.

The string has no effect if the first character is already uppercase.

str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)
Hello
Hello world

center(): The center() method aligns the string to the center as per the parameters given by the user.

In the below example 50 is the padding space

str1 = "Welcome to the Console!!!"
print(str1.center(50))
            Welcome to the Console!!!

We can also provide padding characters. It will fill in the rest of the characters provided by the user.

str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))
............Welcome to the Console!!!.............

count(): The count() method returns the number of times the given value has occurred within the given string.

Example -

str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
4

endswith(): The endswith() method checks if the string ends with a given value. If yes then return True, else return False.

Example -

str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
True

We can even also check for a value in-between the string by providing start and end index positions.

Example:

str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))
True

find(): The find() method searches for the first occurrence of the given value and returns the index where it is present. If the given value is absent from the string then return -1.

Example:

str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))

Output:

10

As we can see, this method is somewhat similar to the index() method. The major difference is that index() raises an exception if the value is absent whereas find() does not.

Example:

str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))

Output:

-1

index(): The index() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then it raises an exception.

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
13

As we can see, this method is somewhat similar to the find() method. The major difference being that index() raises an exception if value is absent whereas find() does not.

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
ValueError: substring not found

isalnum(): The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returns False.

str1 = "WelcomeToTheConsole"
print(str1.isalnum())
True

isalpha(): The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returns False.

str1 = "Welcome"
print(str1.isalpha())
true

islower(): The islower() method returns True if all the characters in the string are lower case, else it returns False.

str1 = "hello world"
print(str1.islower())
True

isupper(): The isupper() method returns True if all the characters in the string are upper case, else it returns False.

str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
True

isprintable(): The isprintable() method returns True if all the values within the given string are printable, if not, then return False.

str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
True

isspace(): The isspace() method returns True only and only if the string contains white spaces, else returns False.

str1 = "        "       #using Spacebar
print(str1.isspace())
str2 = "        "       #using Tab
print(str2.isspace())
True
True

istitle(): The istitle() returns True only if the first letter of each word of the string is capitalized, else it returns False.

str1 = "World Health Organization"
print(str1.istitle())
True
str2 = "To kill a Mocking bird"
print(str2.istitle())
False

startswith(): The startswith() method checks if the string starts with a given value. If yes then return True, else return False.

str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
True

swapcase(): The swapcase() method changes the character casing of the string. Uppercase are converted to lowercase and lowercase to uppercase.

str1 = "Python is a Interpreted Language"
print(str1.swapcase())
pYTHON IS A iNTERPRETED lANGUAGE

title(): The title() method capitalizes each letter of the word within the string.

str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())
He'S Name Is Dan. Dan Is An Honest Man.

Resources Used

You can watch the video of Day#13 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. In this post, we covered almost 22 string methods that are commonly used, among many. There are many methods of string which can be learnt from the official python website below.

Thank you if you read this post and have found this post useful of my learnings from Day #13 of python

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practising coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย