Introduction
The string is one of the sequence data types used in python. It is an immutable object which once created can’t be altered. The string can be denoted by using a single quote (‘ ‘) or double quotes (” “) or triple quotes(” ” “).
In this article, we will know all about string in Python with examples. The contents are shown below :
- Multi-line String
- Strings are Array
- Slicing
- Negative Indexing
- Functions & Methods
- List of methods
- Operator
- String Check
- Format in String
- Escape character
Note that the value of all the strings, as displayed by the Python interpreter, is the same (‘hello’), irrespective of whether single, double or triple quotes were used for string formation.
Since the string is a sequence data type and sequence includes an index in it starting from ‘0’ in order to search a particular item from the sequence. You will be able to see it in the following code.
Multi-line String
Python introduced multiline string using triple quotes (“””) or three single quotes(‘ ‘ ‘)
a = """ The Earth is the most
beautiful planet in the solar
system. There're many creatures
in our Earth."""
print(a)
Strings are Arrays
Strings in Python are arrays of bytes representing characters. Elements of strings can be accessed using square brackets([]).
Slicing
Python supports the range of characters from a string using this technique. The ratio of the starting index and the ending index separated by a semicolon can represent the slicing.
a = "Hey it's Python Tutorial"
print(a[9:15])
Negative indexing
Python also supports negative indexing to start counting from the end of the string.
Look here the index starts from “o” and ends at “i”.
Functions & Methods in String
Some predefined function and methods are there in string and by using them we can perform different kind of operations . They are :
- len(): In order to find the length of a string we normally use this function. The following code will clear your doubts.
a = "Hello, World!"
print(len(a)) #returns 13 including white spaces and special characters
- strip(): This method removes any white space from the beginning to the end of the string.
a = " Hey it's Python Tutorial "
print(a.strip()) # returns "Hey it's Python Tutorial"
- lower(): This converts the entire string into lowercase.
a = "ITIKA"
print(a.lower()) #returns itika
- upper(): This converts the entire string to uppercase.
a = "PYTHON"
print(a.upper()) #returns python
- replace(): This replaces from one string to another.
a = "BOY"
print(a.replace("B" , "T")) #returns TOY
- find(): This method finds the first occurrence of a substring in another string. If not found, the method returns -1.
a= "Python Tutorial"
print(a.find("Tutorial")) #returns 7
a= "Python Tutorial"
print(a.find("Myname")) #returns -1
- count(): This method returns the number of occurrences of a substring in the given string.
a = " " "Meghna wakes up in the morning. Meghna brushes her teeth. Meghna reads books" " "
print(a.count("Meghna")) #returns 3
- isdigit(): This method returns true if all the characters in the string are digits (0-9) if not, it returns false.
a ='2020'
print(a.isdigit()) #returns true
a='26/03/2020'
print(a.isdigit()) #returns false
List of string Methods
- capitalize()
- casefold()
- count()
- encode()
- endswith()
- expandtabs()
- find()
- format()
- format_map()
- index()
- isalpha()
- isalnum()
- isdecimal()
- isdigit()
- isidentifier()
- upper()
- lower()
- isnumeric()
- join()
- isspace()
- isprintable()
- replace()
- partition()
- rfind()
- rindex()
- rjust()
- Istrip()
- Ijust()
- rpartition()
- rsplit()
- rstrip()
- split()
- strip()
- startswith()
- swapcase()
- title()
- translate()
- zfill()
- splitliness
String Operators
Arithmetic operators don’t operate on strings. However, there are special operators for string processing.
- “+”: Appends the second string to the first
a='hello'
b='world' #returns a+b
- “*”: Concatenates multiple copies of the same string
a='hello'
a*3 #returns 'hellohellohello'
- “[: ] “: Fetches the characters in the range specified by two index operands separated by the: symbol
a = 'Python Tutorials'
a[7:16] #returns 'Tutorials'
- “[] “: Returns the character at the given index
a = 'Python Tutorials'
a[7] # returns T
String Check
To check whether a particular character or a phrase is present in a string or not we use in and not in.
#Check if the phrase "ain" is present in the following text
a = "India is also following the global phenomenon."
x = "also" in a
print(a) #returns True
#Check if the phrase "also" is not present in the following text
a = "India is also following the global phenomenon."
x = "also" not in a
print(a) #returns False
String Format
We can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats them, and places them in the string where the placeholders { } are:
quantity = 3
item = 567
price = 49.95
order = "I want {} pieces of item {} for {} rupees."
print(order.format(quantity, item, price)) #returns I want 3 pieces of item 567 for 49.95 #rupees.
Escape Character
An escape character is a backslash \ followed by the character you want to insert.
We will get an error if we use a double quote inside a double quote like this :
But, if we use “\ \” it will not generate any error
The list of escape characters in a string:
- \ – for a single quote
- \\ – for double quote
- \n – newline
- \r – Carriage Return
- \t – for tab
- \b -for backspace
- \f – Form Feed
- \ooo – Octal value
- \xhh – Hex value