Exploring New Techs!

Python – Strings

    

 Hello Technotizers, in this article we will dive deep into python strings and their methods.
String is a sequence of characters enclosed within quotes. In python, strings are enclosed within single or double quotes. ‘name’ and “name”  both are correct strings. A string is displayed by using the print() function.


  • Assign string to a variable:
A string is assigned to a variable by writing the variable name followed by equal sign and the string
.

name = "Harsh" 
print(name)    


  • String as Array:

Each character of a string is considered as a string of length 1 and an element of a list. Characters are accessed by using square brackets containing the index.

name = "My name is Harsh"
print(name[0])           
print(name[6])           

The output is obtained as follows:

    
e     

  • Looping through a string:

As string is a form of an array, a for loop is used for looping through a string.

for a in "Harsh":
    print
(a)     

The output is obtained as follows:

H    
a    
r    
s    
   

  • String slicing:

Slicing is used to get a range of characters from a string. It is like cutting a string into parts. The start index and the end index of the required part is written in square brackets separated by a colon. The character of the end index is not included in the slice. Negative indexes are used to start slicing from the end of the string.

name = "My name is Harsh"
print(name[3:8])         
#slice from the start    
print(name[:7])          
#slice to the end        
print(name[8:])          
#negative indexing       
print(name[-5:-1])       

 The output is obtained as follows:

      NAme      
      My name   
      is Harsh  
      Hars      

  • String Concatenation

 String concatenation is used to combine two strings with each other. The + operator is used to combine strings.

b = "is Harsh"   
name = a+b       
print(name)      
                 
#to add space    
name = a+" "+b   
print
(name)      

The output is obtained as follows:

My nameis Harsh    
My name is Harsh   

  • Format Strings:

Strings and numbers in python are combined using the format() method. The format() method accepts the passed arguments, formats them and places them in the text where the placeholder {} is present.

name = "Harsh"                                      
age = 20                                            
place = "Mumbai"                                    
text = "I am {}, {} years old and stay in {}        
print(text.format(name,age,place))                  
                                                    
#to specify position                                
text = "I am {2}, {0} years old and stay in {1}"    
print(text.format
(age,place,name))                  

The output is obtained as follows:

I am Harsh, 20 years old and stay in Mumbai    
I am Harsh, 20 years old and stay in Mumbai    

  • Escape characters:

Escape characters are used to insert characters that are not allowed in a string. It is written as a backslash \ followed by the character you want to insert.

#to add "" in a string enclosed in "" \" is used    
txt1 = "I'm \"Harsh\""                              
print
(txt1)                                         

The output is obtained as follows:

I'm "Harsh"      

#to add '' in a string enclosed in '' \' is used    
txt2 = 'I\'m Harsh'                                 
print
(txt2)                                         
                                                    

The output is obtained as follows:

I'm Harsh                       
                                
#to add new line \n is used     
txt3 = "I'm\nHarsh"             
print(txt3)                     
                                

  • The output is obtained as follows:

I'm                               
Harsh                             
                                  
#to add a tab space \t is used    
txt4 = "I'm\tHarsh"               
print(txt4)                       
                                  

The output is obtained as follows:

I'm     Harsh                    
                                 
#to add a backspace \b is used   
txt5 = "I'm \bHarsh"             
print
(txt5)                      

The output is obtained as follows:

I'mHarsh        

String Methods:

Python provides various built-in string methods to manipulate strings. 

Note: All string methods return new values and do not change the original string. Do store the new value it should be assigned to a new variable.

       1.      len() method:

       This method returns the length of the string. It also counts the spaces between words into the length.

name = "My name is Harsh"                       
print("The length of the string is:", len(name))
 

The output is obtained as follows:

The length of the string is: 16     

       2.      capitalize() method:

           This method converts the first character of a string into upper case.

name = "my name is Harsh"                         
print("Capitalized string is:", name.capitalize())

The output is obtained as follows:

Capitalized string is: My name is harsh 

3.    upper() method:

This method converts the entire string into uppercase.

name = "my name is harsh"                    
print("Upper cased string is:", name.upper())

The output is obtained as follows:
Upper cased string is: MY NAME IS HARSH  
 
4.      lower() method:
This method converts the entire string into lowercase.

name = "My name is Harsh"                    
print("Lower cased string is:", name.lower())

The output is obtained as follows:
Lower cased string is: my name is harsh  
 
5.       swapcase() method: 
This method swaps the case of the characters in the string. Lower case is converted to upper case and upper case to lower case.

name = "My Name Is Harsh"                      
print("Swap cased string is:", name.swapcase())

The output is obtained as follows:
Swap cased string is: mY nAME iS hARSH  
 
6.      isupper() and islower() methods:
isupper() method returns True if all the characters of the string are upper cased and returns False if not. And islower() method returns True if all the characters of the string are lower cased and returns False if not.

name = " MY NAME IS HARSH"                            
print("Is the string upper cased?:", name.isupper()) 
name = " MY NAME IS HARSH"                           
print("Is the string lower cased?:", name.islower()) 

The output is obtained as follows:

Is the string upper cased?: True 
Is the string lower cased?: False

 
7.      isalnum() method:
isalnum() method returns True if all the characters of the string are alphanumeric that is, having numbers and alphabets and returns False if not. It returns False if whitespaces are present in the string.

name = " My name is Harsh and my age is 20"            
print("Is the string alphanumeric?:", name.isalnum())  
name = " MynameisHarshandmyageitext20"                 
print("Is the string alphanumeric?:", name.isalnum())  
name = " My$nameis?Harshandmyageis*20"                 
print("Is the string alphanumeric?:", name.isalnum())  

The output is obtained as follows:

Is the string alphanumeric?: False
Is the string alphanumeric?: True 
Is the string alphanumeric?: False
 

8. startswith() and endswith() methods:
startswith() method returns True if the string starts with a specified value and returns False if not. And endswith() method returns True if the string ends with a specified value and returns False if not.

name = "My name is Harsh"                                       
print("Does the string start with 'My name'?:", name.startswith("My name"))                                                    
print("Does the string end with 'Harsh'?:", name.endswith("Harsh"))                                                            

The output is obtained as follows:

Does the string start with 'My name'?: True
Does the string end with 'Harsh'?: True    

 
9.      join() method:
This method joins the elements of an iterable to the end of the stings separated by a specific separator if required.

# .join() with lists                          
numList = ['1', '2', '3', '4'               
separator = ', '                              
print(separator.join(numList))                
                                              
# .join() with tuples                         
numTuple = ('1', '2', '3', '4')               
print(separator.join(numTuple))               
                                              
text1 = 'harsh'                               
text2 = '123'                                 
                                              
 # each element of text2 is separated by text 
# '1'+ 'abc'+ '2'+ 'abc'+ '3'                 
print('text1.join(text2):', text1.join(text2))
                                              
# each element of text1 is separated by text2 
# 'a'+ '123'+ 'b'+ '123'+ 'b'                 
print('text2.join(text1):'
, text2.join(text1))
The output is obtained as follows:
1, 2, 3, 4                           
1, 2, 3, 4                           
text1.join(text2): 1harsh2harsh3     
text2.join(text1): h123a123r123s123h 

 
10.  index() method:
This method searches for a value in the string and returns its index or position.

name = "My name is Harsh"                      
print("Index of 'Harsh':", name.index('Harsh'))

The output is obtained as follows:
Index of 'Harsh': 11
 
11.  split() method:
This method splits the string at the specified separator, and returns a list. 
Two parameters, separator and maxsplit shall be given.

name = "My,name,is,Harsh"                        
print("List after splitting:", name.split(','))  
#maximum split 2 is given as parameter           
name = "My,name,is,Harsh"                        
print("List after splitting:", name.split(',',2))

The output is obtained as follows:

List after splitting: ['My', 'name', 'is', 'Harsh'] 
List after splitting: ['My', 'name', 'is,Harsh']    

 
·      Some other methods used in Python strings are tabulated below:


Method

Description

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

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

isalpha()

Returns True if all characters in the string are in the alphabet

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

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

ljust()

Returns a left justified version of the string

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

strip()

Returns a trimmed version of the string

title()

Converts the first character of each word to upper case

translate()

Returns a translated string

zfill()

Fills the string with a specified number of 0 values at the beginning

With this we come to an end of this article. Hope it was helpful.
Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!
Keep coding and exploring new techs!!

0 comments:

Post a Comment