Basics of python strings ##Feed 6

 


Strings are the unicode  characters wrapped in between  quotes either single quotes(' ') or double quotes(" " ) or triple quotes( '''     '''). Strings can be sorted according to alphabetical order.

1. Creating a string variable named str_var.

>> str_var= "This is a string"
>> str_var

Output:
 'This is a string'

Note the output is displayed with single quotes indicating the output is a string. If we miss the quotes in the string variable the output returns an error.
** If we give numbers in quotes, python will consider those numbers as string since they are under quotes(' ')


2. Length of string:
Syntax:
 len(string_variable)

Ex: Let's check how many characters are there in str_val.
>> len(str_var)
Output:
16
Here len() function calculates spaces also as characters. So count all the characters along    with spaces and it is 16.


3. Datatye of string:
Syntax:

type(string_variable)
Ex: Check the data type of str_var.
>> type(str_var)
Output:
str


4. Indexing in strings:
We already learnt about indexing in our previous posts in arrays. 
If you have not gone through indexing topic in python, please go through this link.
https://spacewidget.blogspot.com/2021/09/indexing-in-python-must-know-these-tips.html

Ex: Let's print only the first character from  str_val.
>> str_var[0]
Output:
'T'

Ex: Let's print the word "string" from  str_val.
>> str_var[-6:]
Output:
'string'
Similarly we can access all the characters of the str_var. 

Ex: Access all the elements except "This" from str_var.
>> str_var[4:]
Output:
' is a string'
Here the word "This" is a four character word and index of the word starts from 0 and ends at 3. Index 4 is a space character and in result we can see space before 'is'.

5. Built-in Methods for strings:
a) Converting the string variable into lower case letters.
Syntax: 
string_variable.lower( )
Ex: Convert all characters in str_var to lower case.
>>str_var.lower( )
Output:
'this is a string'

b) Converting the string variable into upper case letters.
Syntax: 
 string_variable.upper( )
Ex: Convert all characters in str_var to upper case.
>>str_var.upper( )
Output:
'THIS IS A STRING'

c) Converting the string variable into upper case letters.
Syntax: 
 string_variable.swapcase( )
Ex: Convert lowercase to uppercase characters and upper case to lower case characters  in str_var.
>>str_var.swapcase()
Output:
'tHIS IS A STRING'

d) Removing spaces from the start and end of the  string variable.
Syntax: 
 string_variable.strip( )
Here we are creating a new variable str_var1 as the string created in the previous        example have no gaps at the start and end of the strings.
Ex: Create a new string variable and remove the gaps present at the start and end of the       string.
>>str_var1='    There is a gap befor ans after the string    '
>>str_var1
Output:
'    There is a gap before and after the string    '
Observe there were gaps in the string shown in orange color inside the single quotes. Now we have to remove the gaps.
>>str_var1.strip( )
Output:
'There is a gap before and after the string'
The gaps or spaces that are present at the start and end of the strings were removed after the application of strip() method.

e) Splitting the characters or words in the string variable.
Syntax: 
 string_variable.split( delimiter )
Ex: Create a new string variable and split the words in that string .
>>str_var2= 'Roll No. is 140'
>>str_var2
Output:
'Roll No. is 140'
>>str_var2.split()
Output:
['Roll', 'No.', 'is', '140']
As we have not mentioned the delimiter as arguement, space is considered as default delimiter and the words seperated by space were displayed in the output.

f) Sorting in strings:
Syntax:
sorted(string_variable)
Sorting is case sensitive. Capitals(upper case)letters are sorted first then lower case letters will be sorted. 
If a string is a combination of spaces, numbers, upper and lower case characeters then          sorting will follow the priority order. The string will split all the characters in the string and then  aligned according to the priority.
Priority of sorting the characters in strings:
    spaces > numbers > upper case letters > lower case letters
Ex: Sort all the characters in the strinng str_var2.
>> sorted(str_var2)
Output:
[' ', ' ', ' ', '.', '0', '1', '4', 'N', 'R', 'i', 'l', 'l', 'o', 'o', 's']
Observe the output . We can see all the characters in the string (str_var2) were splitted first  and are arranged in priority.

g) Finding if all the characters in the string are similar or not:
1) string_variable.isalpha()
This methods returns 
"True"-- if all the characters in the string are alphabets and returns       
 "False" --if there is atleast 1 number or space or any special character.
Ex: Check if all the characters in str_var2 are alphabets?
>> str_var2.isalpha()
Output:
False
Since str_var2 is a combination of chracters, numbers and spaces. It returns False as output.

2) string_variable.isdigit()
This methods returns 
"True"-- if all the characters in the string are digits and 
"False"-- if there is atleast 1 alphabet or space or any special character.
Ex: Check if all the characters in str_var2 are numbers?
>> str_var2.isdigit()
Output:
False

3) string_variable.isspace()
This methods returns 
"True"--if all the characters in the string are spaces and
 "False" -- if there is atleast 1 character other than space.
Ex: Check if all the characters in str_var2 are spaces?
>> str_var2.isspace()
Output:
False

h)Changing or replacing the objects in the string:
Syntax:
string_variable.replace("old_name", "new_name")
Ex: Create a array of fruits and replace "Apple" with "Papayya".
>>Fruits=" 'Apple','Banana','Pineapple','strawberry','orange'"
>>Fruits
Output:
"'Apple','Banana','Pineapple','strawberry','orange'"
Here the each of the fruit name is a string and are denoted with single quotes. Fruits is a variable name which is a collection of individual fruits (strings). We know string variables must be in quotes, but we already used single quotes for representing fruit names, we are using    double quotes for representing the collection of fruits i.e., Fruits. 
>>Fruits.replace('Apple', 'Papayya')
Output:
"'Papayya','Banana','Pineapple','strawberry','orange'"
In result "Apple" is replaced with "Papayya".

i)Finding the index of the objects available in  string variable.
Syntax:
string_variable.find("object to be searched")
find() functions returns the  starting index of the word searched.

Ex: Tell us the  start index of the "Apple"  in Fruits.
>> Fruits.find('Apple')
Output:
1
Here index 0 refers to single quote, so the word "Apple" starts with index 1 instead of 0.

Ex: Tell us the  start index of the "Pineapple"  in Fruits.
>> Fruits.find('Pineapple')
Output:
18

Here output is 18, it means the word "Pineapple" starts at index 18. Count all the 
single quotes, characters and commas from index 0 and we can find the first letter
in "Pineapple" i.e., P is at index 18. 

j)string_variable.startswith()
Ex: Check if the string variable named Fruits started with single quote. 
>>Fruits.startswith(" ' ")
Output:
True
Remember no space inside the double quotes. If there are spaces the output is False as the string Fruits starts with single quote (')
Ex: Check if the string variable named Fruits started with "Apple". 
>>Fruits.startswith("Apple")
Output:
False
As the string variable starts with single quote,  it returns False.

k) string_variable.endswith()
Ex: Check if the string variable named Fruits ends with "orange". 
>>Fruits.endswith("orange")
Output:
False
Ex: Check if the string variable named Fruits ends with single quote. 
>>Fruits.endswith(" ' ")
Output:
True

l) string_variable.join()
Join() is opposite to split() function. It returns all the objects in the string joined by the given seperator.
Ex: Join all the characters in the string with a sepeartor '-'.
>>seperator='-'
>>seperator.join(Fruits)
Output:
"'-A-p-p-l-e-'-,-'-B-a-n-a-n-a-'-,-'-P-i-n-e-a-p-p-l-e-'-,-'-s-t-r-a-w-b-e-r-r-y-'-,-'-o-r-a-n-g-e-'"

To return to original state we can use split() function which was described in the  above        examples.
>>Fruits.split('-')
Output:
["'Apple','Banana','Pineapple','strawberry','orange'"]


These are the basic string operations in python.
Happy learning...Keep moving...😊

Comments