Python Strings | Strings in Python



#--------------------------->Strings<-----------------------------

#String Concatenation
f_name="Chrome"
l_name="browser"
print(f_name + " " + l_name)
var="Kali Linux"
print(var + "3.7")
print(var+str(3.7))
print(f_name*3) # It'll print Chrome 3 times.
#String Formatting
name = "Rakshit"
age = 5
print(f"Hello {name} your age is {age+2}")
#------------------output----------------
# Chrome browser
# Kali Linux3.7
# Kali Linux3.7
# ChromeChromeChrome
# Hello Rakshit your age is 7

#-----------------String Indexing------------------

name="Chrome"
print(name[0])
print(name[-1])
print(name[0:])
print(name[-1::-1]) #Reverse/Backward
print(name[::-1]) #Reverse
print(name[0::2]) #increment string index by 2
print("Rakshit"[0:])
print("I'manonymous"[0::2]) # 2 indicates 2 steps
#---------Output----------
# C
# e
# Chrome
# emorhC
# emorhC
# Crm
# Rakshit
# Imnnmu

#------------String Methods------------
name="It's Me rakShit"
print(len(name))
print(name.lower())
print(name.upper())
print(name.title())
print(name.lower().count("s"))#It's count number of occurance of "s"
#----------Output--------------------
# 15
# it's me rakshit
# IT'S ME RAKSHIT
# It'S Me Rakshit
# 2
#************************Strip Method**************************
name=" Kali "
name2=" Li ux "
dots="......................."
print(name+dots)
print(name.lstrip()+dots) #It's removing left side space of kali
print(name.rstrip()+dots) #It's removing right side space
print(name.strip()+dots) #It's removing both side space
print(name2.replace(" ","")) # It's replacing " " by ""
print(name2.replace(" ","_"))
string="My name is Noah"
print(string.replace(" ","_"))
string2="Linux is my girlfriend"
print(string2.replace("is","was"))
string3="She is my girlfriend is not now is"
print(string3.find("is"))
occ=string3.find("is")
#It's finding "is" starting index after one time occurance.
print(string3.find("is",occ+1))
print(len(string2.replace(" ","")))
#----------output-----------
# Kali .......................
# Kali .......................
# Kali.......................
# Kali.......................
# Liux
# _______Li_________ux___________
# My_name_is_Noah
# Linux was my girlfriend
# 4
# 21
# 19

#*******************************Center Method***********************
name = "Kali Linux"
print(name.center(16,"*"))
#Output:
# ***Kali Linux***

Comments