Strings In Python
Last updated
Last updated
Python string is the collection or sequence of the characters surrounded by single quotes(' '), double quotes(" "), or triple quotes(''' '''),(""" """).
In more simpler terms , whatever you write between these quotes are String. For Example:</span>
In [ ]:
Single line strings are written under single quotes '' and double quotes "". They appear as a single line on console screen. For Example:
In [3]:
Multiline line strings are written under triple quotes ''' ''' and """ """. They appear in multiple lines such as paragraphs. For Example:
In [6]:
Memory allocation of Numbers : A number (integer or float) gets stored in a memory block and gets associated with a variable as soon as we define it. For Example:
In [ ]:
Memory Allocation of Strings : As we know that strings are a sequence of characters, hence Each character of string gets store in different memory block, something like this:
In [ ]:
As we know that characters of strings are stored in different memory blocks, each character within a string is given an index number.
Python offers two different indexing :
Positive Index Numbers : Positive index numbers starts from zero (0) and left to right.
As we know that characters of a string are identified by their index number, so we can access characters with the help of character's index numbers.
For Example in name = 'abhi', to get character 'a' from a string 'abhi' , we will type name[0].
In [8]:
Suppose there is a long string and we need to access character at the end of the string, instead of using positive indexing , negative indexing would be much more helpful. For Example:
In [10]:
To get 'E' from sentence with the help of Positive indexing would be tough rather than accessing character with the help of negative indexing.
In [11]:
Out[11]:
Slicing of a string means taking a substring or part of a string from it. For example , 'Console' is a substring of 'Console Flare'. Index numbers should always be in ascending orders.
Slicing of a string is done like this : variable[starting index : ending index]. Here ending index should be one index number more than the last character's index number.
In more simpler terms in name = "abhishek", "abhi" from "abhishek" can be sliced as name[0:4].
In [12]:
Out[12]:
variable[starting index : ending index : step size(n)], here steps mean, it takes every n step starting from starting index. Default value of step is 1.
In [13]:
Out[13]:
Default Value of Starting index is 0.If we don't write anything as Starting index while slicing , it takes 0 as default. For Example:
In [14]:
Out[14]:
Default Value of Ending index is end of string.If we don't write anything as ending index while slicing , it takes end of string as indexing. For Example:
In [15]:
Out[15]:
Default Value of Step size is 1 and is optional , we need to use step size only if we want it to skip characters in a string.
In [16]:
Out[16]:
Negative slicing of a string means to slice the string with the help of negative indexes. Here also , index numbers should always be in ascending order. For Example:
In [18]:
Out[18]:
formatting strings lets you use embedded Python expressions inside string. Here’s a simple example to give you a feel for the feature:
In [86]:
f'string and expressions': This is how you can merge expressions and string in a single string.
len() function:
len() function is used to count characters in a string. For Example:In [19]:
Out[19]:
max() function:
max() function is used to return largest value or character in a string , For Example:In [22]:
Out[22]:
max() function can also return largest alphabetic character based on their ascii code. You can go through ASCII codes of different alphabets through here. For Example:
In [23]:
Out[23]:
ASCII Code of 's' is 115 , largest than any other character's.
min() function:
min() function is used to return smallest value or character in a string , For Example:In [25]:
Out[25]:
To Understand String Methods better , first we will have to know what are methods.
Methods are nothing but Type - Specific Function. Methods are functions that only work for a particular data type.
In more Simpler terms, String methods are functions that will only work for strings. String methods are used for handling strings , performing operations on string , string manipulation etc.
Note: All String methods return new values and does not change original string.
lower() method is used to return string with all its character in lowercase. We do not pass any paramters in lower(). For Example:
In [27]:
upper() method is used to return string with all its character in Capital case. We do not pass any paramters in upper(). For Example:
In [28]:
swapcase() method is used to return string with all its character in lower to upper case and all its string in upper to lower case. It does not have any parameters. For Example:
In [29]:
The title () method in python is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string. It does not have any paramters. For Example:
In [31]:
capitalize() method return string with its first character as upper case and rest in lower case. It does not have any parameters. For Example:
In [32]:
strip() method removes all the whitespace from left and right side of the string.
lstrip() method removes all the whitespace from left side of the string.
rstrip() method removes all the whitespace from right side of the string.
In [81]:
In [82]:
It removed all whitespaces from left side of string.
In [84]:
It removed all whitespaces from right side of string.
replace() method returns a string where a specified value is replace with a specified value.
Parameters to be passed in replace:
oldvalue: The string to be replaced. It is Required
newvalue : The string to replace the old value with. It is Required
count: An integer value specifying how many occurences of the old string you want to replace. Default value of count is All Occurences. It is Optional
replace(oldvalue,newvalue,count)
In [35]:
To replace 'C Language' with 'Python Programming Language' , we will use replace() method.
In [36]:
To see , How count works, i will be using count parameter in below example:
In [37]:
count() method returns the number of times a specified value occurs in a string.
Parameters to be passed in count():
value : substring or value to count. It is Required.
start index : The position from where to start the search. It is Optional. Default value is 0.
end index : The position from where to end the search.It is Optional. Default value is the end of the string.
count(value,start,end)
In [41]:
To see , How start and end paramters work , i will be using them in below example:
In [40]:
find() method searches the string for a specified value and returns the starting position of where it is found. It searches the whole string for specified value from left to right.
In more simpler terms, it finds the string's position.
Parameters to be passed inside find() method:
value : The values to search for. It is Required.
start : Starting index, from where to look for the value. It is Optional
end : Ending index, from where to stop the search for value. It is Optional
find(value,start,end)
In [45]:
To see , How start and end paramters work , i will be using them in below example:
In [47]:
Hence, the operation of start and end is same everywhere, it looked for 'python' from index number 1 to 18.
rfind() method is same as find() method with same parameters. The only difference is it looks for specified string from right to left. For Example:
In [49]:
index() method also searches the string for a specified value and returns the position of where it is found.
In more simpler terms index() works like find() and rindex() works like rfind(). They both have same parameters. For Example:
In [50]:
In [51]:
find() does not give error, when value or substring is not found and flow of the program does not interrupt.
index() gives error when value or substring is not found. for Example:
In [53]:
In [55]:
split() method splits the string at the specified separator and returns a list(We will cover list in upcoming lessons. It is another data type.)
Parameters to be passed in split():
separator : Specifies the separator to use when splitting the string. It is Optional.By Default , any whitespace is separator.
maxsplit : maxsplit specifies how many splits to do . It is Optional.It's Default value is -1 or All Occurences
In [56]:
To see , How maxsplit work , i will be using them in below example:
In [57]:
rsplit() works like split() , it also splits the string from right to left. For Example:
In [58]:
if you use split() and rsplit() method on a same string you will find there is no difference in output. let's use them both on a single string:
In [59]:
split() splits the string from left to right and rsplit() splits the string from right to left , yet output is same always.
Difference between split() and rsplit() can only be shown with maxsplit(). let's follow these examples:
In [63]:
In [64]:
Because rsplit() splits the string from right to left , maxsplit gives different result from split() method.
partition() method returns string where string is parted into three parts:
1.Everything before the first separator 2.Separator itself. 3.Everything after the first separator.
Parameter to be passed into method: separator
partition(separator)
In [66]:
Note:rpartition() is same as partition() , only it starts from right to left.In [67]:
islower() returns True if all the characters in string is lowercase , otherwise it returns False. It has no Parameters.
In [68]:
isupper() returns True if all the characters in string is uppercase , otherwise it returns False. It has no Parameters.
In [69]:
isalpha() returns True if all the characters in string is only alphabets , otherwise it returns False. It has no Parameters.
In [70]:
isnumeric() returns True if all the characters in string is only numbers , otherwise it returns False. It has no Parameters.
In [72]:
isalnum() returns True if all the characters in string is either number or string or both , otherwise it returns False. It has no Parameters.
In [73]:
startswith() returns true if the string starts with a specified value.
Parameters to be Passed in method:
value : The values to check if the string starts with. It is Required
start : An integer specifying at which position to start the search. It is Optional
end : An integer specifying at which position to end the search. It is Optional
In [74]:
endswith() returns true if the string ends with a specified value.
Parameters to be Passed in method:
value : The values to check if the string ends with. It is Required
start : An integer specifying at which position to start the search. It is Optional
end : An integer specifying at which position to end the search. It is Optional
In [75]: