Welcome guys. in this blog post we are going to learn about the strings in python , their behavior , initialization, methods and also some recipes for solving problems related to strings.
basic intro to python .
Before going on to strings let me give you a brief intro to python . ( you can skip this part if you have a notion about it).
Python is a high levelnterpreted and object oriented language. By object oriented means every thing in python from data structures to functions and classes is treated as objects.
wikipedia defines an object as:
" An object is an abstract data type with the addition of polymorphism and inheritance. . An object has state (data) and behavior (code) "
Variables in python are dynamically typed which means we don’t declare the type of variable. It checks the kind of variable in the runtime of the program.
Getting deep into this is beyond the scope of this post. But surely I would like to write a separate post about it .
So, what are strings in python ?
As everything in python is an object , so are strings.
Strings are immutable sequence objects where each character represents an element in the sequence .
Basic example of a string.
greeting = "have a nice day"
Explaining it a little , Immutable in case of string means that once an string object is initialized in memory . we cannot change it .. but still we can manipulate it with many builtin methods . but the original string object remains unchanged whilst a copy of it is returned . As a simple rule of thumb any method that manipulates an string returns a copy of it..
By sequence we mean a string object is indexable and iterable like an list ( we talk about it later) .which mean we can access an element of string object (which is basically a character) by its index and iterate the through the individual values in a loop .
lets see this in action
#indexing greeting #>> h #we can also take a slice of the string due to its indexing properties greeting[0:3] #>> have #iterating through a string for char in greeting[0:3]: print(char) #>> h #>>a #>>v #>>e # remember index starts from 0i
Some useful methods of Strings
Strings in python are packed with many powerful methods .which makes our life lot better while manipulating them .
Here I am going to show you some of the most useful methods associated to strings.
Note: in the code block #» some value represents the return from terminal or python REPL
Methods for changing the case of the string.
greeting = 'have a nice day' greeting.capitalize() # captalizes the first character of the string #>> Have a nice day greeting.swapcase() #inverses the case of each character of a string #>>HAVE A NICE DAY greeting.title() # captalizes the first character of each word in the string # >> Have A Nice Day greeting.upper() # captalizes every character of the string # >> HAVE A NICE DAY greeting.lower() # changes the case to lower for every character in the string #>> have a nice day
Methods for finding & replacing in strings.
greeting.count("nice") #return the number of times the substring is present in the string #>> 1 greeting.endswith("day") #return a boolean whether the string ends with the substring #>> True greeting.startswith("day") #return a boolean whether the string starts with the substring #>> False greeting.find("day") # Return the lowest index in S where substring sub is found, #>> 12 greeting.split("") # Return a list of the words in the string, using sep as the delimiter string.here the sep used is a space #>> ['have', 'a' ,'nice', 'day'] greeting.replace("nice","bad") #Returns a copy of the string with all occurrences of substring old replaced by new. #>> have a bad day words=['have','a','nice','day'] #we have a list of words that we need to concat with with space between the words. greeting=" ".join(words) #here we call call the join method of a string with a blank space. print(greeting) #as we see string.join() insert the the string between every word(string) in the list #>> "have a nice day"
methods to strip spaces from a string.
greeting='have a nice day ' greeting.rstrip() #remove the blank space from the rightside #>> 'have a nice day' greeting=' have a nice day' greeting.lstrip() #remove the blank space from the left side #>> 'have a nice day' greeting=' have a nice day ' greeting.strip() #remove the blank space from the both sides #>> 'have a nice day'
Recipes for string manipulation.
Creating a string out of a list of string or any other iterable.
There are numerous ways to create a string out of list of strings. like we can use a loot and add each character to a blank string .
But the python string object has a powerful and optimized method for such requirements and that is the string.join(iter) .Which takes an iterable as the argument . The string whose method is called is inserted in between each given string. The result is returned as a new string.
let me show you an example:
suppose we have a list of strings : [“have”, “a, “nice” , “day”] and we want to concat it into a string with space between each word.
words=['have','a','nice','day'] #we have a list of words that we need to concat with with space between the words. greeting=" ".join(words) #here we call call the join method of a string with a blank space. print(greeting) #as we see string.join() insert the the string between every word(string) in the list #>> "have a nice day"
creating list out of characters in string.
As strings in python are iterable calling the builtin list function returns a list of characters in the string.
alphabet_string="abcdefghijklmnopqrstuvwxyz" alphabet_list= list(alphabet_string) print(alphabet_list) #>> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Thanks for reading till end. stay tuned for new tutorials in this series. ( data structures in python) , will be sharing new posts daily.
Have a great coding day 🥰.