String Data type in Python
In this blog, we will study about strings in Python. String is a built in datatype which is a sequence of characters.
#Create a string
mystring="DataScience"
print(mystring)
#Here, DataScience is a string
#String can contain a single or multiple characters.
mystring1= 'I love Data Science'
print(mystring)
#To check the datatype of any variable, we can use the type function.
mystring="DataScience"
print(type(mystring))
#O/t- <class 'str'>
#str means string data type
String can contain alphabets, special characters and numerics also. Further, whenever we provide any input to Python, it is by default taken as a string.
#Can contain any numerics
mystring1="DataScience100"
print(type(mystring1))
#O/t - <class 'str'>
#Can contain any special character
mystring2="DataScience100@gmail.com"
print(type(mystring2))
#O/t - <class 'str'>
#only numerics within a single quote can also be treated as a string
mystring3='1234'
print(type(mystring3))
#O/t - <class 'str'>
#without a quote, it will be an integer
mystring4=1234
print(type(mystring4))
#O/t -<class 'int'>
Let’s discuss about
- String Initialization
- Accessing String
- Editing a String
- Deleting a String
- Operators can be applied on String
- Functions can be performed on String
String Initialization:
Strings can be initialized within either single quotes (‘’), double quotes (“ “), or triple quotes (‘’’ ‘’’ or “”” “””).
#Examples - how to intialize a string
mystring= 'I love Data Science'
print(mystring)
mystring= "I love Data Science"
print(mystring)
mystring= '''I love Data Science'''
print(mystring)
mystring= """I love Data Science"""
print(mystring)
Accessing String:
- Indexing: String can be accessed by Positive indexing or negative indexing. Ineding refers to the positioning of any characters in a word. As Python follows zero based indexing, the first character starts with positive indexing. However, negative indexing starts with -1.
#Indexing
#Positive Indexing/Zero based Indexing
mystring="Python"
mystring[0]
#O/t- P
#P-0, y-1, t=2, h-3, o-4, n-5
#Negative Indexing
mystring[-3]
#O/t- h
2. Slicing: Slicing is a technique used to extract a portion of a string by specifying a range of indices. It can be done wither by positive indexing or negative indexing.
#1. Basic Slicing #syntax[start index:end index]
mystring="Python"
mystring[1:4]
#O/t- yth
#Omitting the end
mystring[1:]
#O/t- ython
#Omitting the start
mystring[:5]
#O/t- Python
#Slicing with a step
mystring[::2]
#O/t- Pto
#Slicing using Negative indexing
mystring[-4:-1]
tho
#Negative Slicing with a step size
mystring[:-3:3]
P
#Reverse a string using negative indexing
mystring[-1:-7:-1]
nohtyP
#Reverse the whole string
mystring[::-1]
nohtyP evoL
The advantage of using negative indexing is that you can access the string from the end even without knowing its length.
Editing a String:
String is immutable i.e. once it is created it cannot be edited.
#Immutability- a string can never be edited
#Editing a String
str1="I love Python"
str1[0]='u'
print(str1)
#This will show an error - TypeError: 'str' object does not support item assignment
Deleting of a String:
A string can not be edited but it can be deleted using del keyword.
#Deleting a String
print(str1)
del str1
print(str1)
Operators on String:
Arithmetic operators (Additional and multiplication only), Relational Operators, and Membership operators can be applied on a string.
#Arithmetic Operator- +, *
mystring1="I love"
mystring2="Python"
print(mystring1 + mystring2) #This will concatenate the String
print(mystring1*3) #This will print the string 3 times
I lovePython
I loveI loveI love
#Relational Operators
#Every Relational Operators works on string based on ASCII value
str1="Love"
str2="Python"
print(str1<str2)
#Membership Operator- in, not in
a=['apple', 'banana', 'jack fruit', 'grapes']
if 'apple' not in a:
print("apple is a member")
else:
print("not a member")
#O/t- apple is a member
Functions on String
#len() - It provides the length of a string
str1= "I love Python"
len(str1)
#O/t- 13
#max()- It compares the ASCII value of the first character of strings
a=['apple', 'banana', 'jack fruit', 'grapes']
print(max(a))
#O/t- jack fruit
#ASCII value of j is greater than the ASCII value of first characters of other words
#min()
print(min(a))
#O/t- apple
#sorted() #To Sort the characters alphabetically
str1='PYTHON'
print(sorted(str1))
#O/t- ['H', 'N', 'O', 'P', 'T', 'Y']
#capitalize() #To capitalize the first letter of every sentence
str1="i love python"
print(str1.capitalize())
#O/t- I love python
#title() #To capitalize the first character of every word
str1="i love python"
print(str1.title())
#O/t- I Love Python
#upper() # To change the characters into uppercase
str1="i love python"
print(str1.upper())
#O/t- I LOVE PYTHON
#lower() # To change the characters into lowercase
str2="I LOVE PYThon"
print(str2.lower())
#O/t- i love python
#swapcase()
str1="I love pytHON"
print(str1.swapcase())
#O/t- i LOVE PYThon
#count - To count how many times a specific word or character appears in a sentence
str1="I love love Python"
print(str1.count("love"))
#O/t- 2
#find- gives the index position of any given word
str1="I love Python"
print(str1.find("Python"))
#O/t- 7
#startswith - To check whether the string starts with the given set of characters
str1= "I love Python"
print(str1. startswith("I love"))
#O/t- True
#endswith- To check whether the string ends with the given set of characters
str1= "I love Python"
print(str1.endswith("python"))
#O/t- False
#isalnum()- To check whether the string contains alphabet or numeric digits
str1= "100"
print(str1.isalnum())
#O/t- True
#isdigit() - To check whether the string contains only numeric digits
str1= "1009937986327845237"
print(str1.isdigit())
#O/t- True
#split() - To split any sentence based on any given delimeter
str1= "I, love/ Python so, much"
print(str1.split(' '))
#O/t- ['I,', 'love/', 'Python', 'so,', 'much']
#join() #To join a set of words based on delimeters
str1=['I ', 'love', 'DataScience']
sentence= '0'.join(str1)
print(sentence)
#O/t- I 0love0DataScience
#replace #To replace any desired word by another word
str1="I love Python"
print(str1.replace("I", "He"))
print(str1)
#O/t- He love Python
#strip - To delete the spaces at the beginning and at the end of any sentence
str1= " I love Python "
print(str1.strip())
#O/t- I love Python
We have discussed everything related to a string. There are many other functions also which can be applied on strings.
Free explanation of String in my channel.
Download the code from my github link- https://colab.research.google.com/drive/1W7R73X5ORdmeAg6FqxF2SheeCiu4t_JN