Python Strings and String Function in Python
Python string is an ordered collection of characters that is used to represent and store text-based information. Strings are stored as individual characters in a contiguous memory location. It can be accessed from both directions: forward and backward. Characters are nothing but symbols. Strings are immutable Data Types in Python, which means that once a string is created, it cannot be changed. In this module, we will learn all about strings in Python so as to get started with strings.
Watch this video on Python String Operations:
So, without any further ado, let’s get started.
Creating a String in Python
In Python, strings are created using either single quotes or double-quotes. We can also use triple quotes, but usually triple quotes are used to create docstrings or multi-line strings.
#creating a string with single quotes
String1 = ‘Intellipaat’
print (String1)#creating a string with double quotes
String2 = “Python tutorial”
Print (Strings2)
After creating strings, they can be displayed on the screen using the print () method as shown in the above example. The output of the above example will be as follows:
Intellipaat
Python Tutorial
Kick-start your career in Python with the perfect Python Course in New York now!
Accessing Python String Characters
In Python, the characters of string can be individually accessed using a method called indexing. Characters can be accessed from both directions: forward and backward. Forward indexing starts form 0, 1, 2…. Whereas, backward indexing starts form −1, −2, −3…, where −1 is the last element in a string, −2 is the second last, and so on. We can only use the integer number type for indexing; otherwise, the TypeError will be raised.
Example:
String1 = ‘intellipaat’
print (String1)
print (String1[0])
print (String1[1])
print (String1[-1])
Output:
Intellipaat
i
n
t
Python is one of the most demanding skills right now in the market. Enroll in our best Python training in Bangalore and become a Python Expert.
Updating or Deleting a String in Python
As discussed above, strings in Python are immutable and thus updating or deleting an individual character in a string is not allowed, which means that changing a particular character in a string is not supported in Python. Although, the whole string can be updated and deleted. The whole string is deleted using a built-in ‘del’ keyword.
Example:
#Python code to update an entire string
String1 = ‘Intellipaat Python Tutorial’
print (“original string: “)
print (String1)String1 = ‘Welcome to Intellipaat’
print (“Updated String: “)
print (String1)
Output:
Original String:
Intellipaat Python Tutorial
Updated String:
Welcome to Intellipaat
Example:
#Python code to delete an entire string
String1 = ‘Intellipaat Python tutorial’
print (String1)
del String1
print (String1)
Output:
Intellipaat Python tutorial
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘String1’ is not defined
Go for the most professional Python Course Online in Toronto for a stellar career now!
There are three types of operators supported by a string, which are:
- Basic Operators (+, *)
- Relational Operators (<, ><=, >=, ==, !=)
- Membership Operators (in, not in)
Table: Common String Constants and Operations
Operators |
Description |
s1 = ‘ ’ |
Empty string |
s2 = “a string” |
Double quotes |
block = ‘‘‘…’’’ |
Triple-quoted blocks |
s1 + s2 |
Concatenate |
s2 * 3 |
Repeat |
s2[i] |
i=Index |
s2[i:j] |
Slice |
len(s2) |
Length |
“a %s parrot” % ‘dead’ |
String formatting in Python |
for x in s2 |
Iteration |
‘m’ in s2 |
Membership |
Get 100% Hike!
Master Most in Demand Skills Now!
Table: String Backslash Characters
Operators |
Description |
newline |
Ignored (a continuation) |
n |
Newline (ASCII line feed) |
\ |
Backslash (keeps one ) |
v |
Vertical tab |
’ |
Single quote (keeps ‘) |
t |
Horizontal tab |
” |
Double quote (keeps “) |
r |
Carriage return |
a |
ASCII bell |
f |
Form feed |
b |
Backspace |
�XX |
Octal value XX |
e |
Escape (usually) |
xXX |
Hex value XX |
�00 |
Null (doesn’t end string) |
Example: Program to concatenate two strings.
S1 = “hello”
S2 = “Intellipaat”
print (S1 + S2)
Become a Professional Python Programmer with this complete Python Training in Singapore!
Built-in Python String Methods and Python String Functions
Let’s understand some Python String Functions and standard built-in methods
Python String Length
len() function is an inbuilt function in the Python programming language that returns the length of the string.
string = “Intellipaat”
print(len(string))
The output will be: 11
string = “Intellipaat Python Tutorial”
print(len(string))
The output will be: 27
Python Slice String
To use the slice syntax, you have to specify the start and the end index, separated with a colon. The required part of the string will be returned.
a = “Intellipaat”
print (a[2:5])
The output will be: tel
Slice from the Starting
If you leave out the start index, the range will be started from the first character.
a = “Intellipaat”
print (a[:5])
The output will be: Intel
Slice from the Ending
If you leave out the start index, the range will be started from the first character.
a = “Intellipaat”
print (a[2:])
The output will be: tellipaat
Python Reverse String
There isn’t any built-in function to reverse a given String in Python but the easiest way is to do that is to use a slice that starts at the end of the string, and goes backward.
x = “intellipaat” [::-1]
print(x)
The output will be: taapilletni
Python Split String
The split() method lets you split a string, and returns a list where each word of the string is an item in the list.
x=”Intellipaat Python Tutorial”
a=x.split()
print(a)
The output will be: [‘Intellipaat’, ‘Python’, ‘Tutorial’]
By default, the separator is any whitespace, but it can be specified otherwise.
Python Concatenate Strings
The + operator is used to add or concatenate a string to another string
a = “Python tutorial”
b = “ by Intellipaat”
c = a + b
print(c)
The output will be: Python tutorial by Intellipaat
Python Compare Strings
We can compare Strings in Python using Relational Operators. These operators compare the Unicode values of each character of the strings, starting from the zeroth index till the end of the strings. According to the operator used, it returns a boolean value.
print(“Python” == “Python”)
print(“Python” < “python”)
print(“Python” > “python”)
print(“Python” != “Python”)
The outputs will be:
True
True
False
False
Python list to string
In python, using the .join() method, any list can be converted to string.
a = [‘Intellipaat ’, ‘Python ’, ‘Tutorial ’]
b = “”
print(b.join(a))
The output will be: Intellipaat Python Tutorial
Learn the easy way to take list input in Python and master the simple techniques for handling lists.
Python String Replace
The replace() method in Python will replace the specified phrase with another.
a = ”I like Programming”
b = a.replace(“Programming”, “Python”)
print(b)
The output will be: I like Python
Go through the following table to understand some other Python String Methods:
String Method/String Function in Python |
Description of String Method/String Function in Python |
capitalize() |
It capitalizes the first letter of a string. |
center(width, fillchar) |
It returns a space-padded string with the original string centered to. |
count(str, beg= 0,end=len(string)) |
It counts how many times ‘str’ occurs in a string or in the substring of a string if the starting index ‘beg’ and the ending index ‘end’ are given. |
encode(encoding=’UTF-8′,errors=’strict’) |
It returns an encoded string version of a string; on error, the default is to raise a ValueError unless errors are given with ‘ignore’ or ‘replace’. |
endswith(suffix, beg=0, end=len(string)) |
It determines if a string or the substring of a string (if the starting index ‘beg’ and the ending index ‘end’ are given) ends with a suffix; it returns true if so, and false otherwise. |
expandtabs(tabsize=8) |
It expands tabs in a string to multiple spaces; defaults to 8 spaces per tab if the tab size is not provided. |
find(str, beg=0 end=len(string)) |
It determines if ‘str’ occurs in a string or in the substring of a string if starting index ‘beg’ and ending index ‘end’ are given and returns the index if found, and −1 otherwise. |
index(str, beg=0, end=len(string)) |
It works just like find() but raises an exception if ‘str’ not found. |
isalnum() |
It returns true if a string has at least one character and all characters are alphanumeric, and false otherwise. |
isalpha() |
It returns true if a string has at least one character and all characters are alphabetic, and false otherwise. |
isdigit() |
It returns true if a string contains only digits, and false otherwise. |
islower() |
It returns true if a string has at least one cased character and all other characters are in lowercase, and false otherwise. |
isupper() |
It returns true if a string has at least one cased character, and all other characters are in uppercase, and false otherwise. |
len(string) |
It returns the length of a string. |
max(str) |
It returns the max alphabetical character from the string str. |
min(str) |
It returns the min alphabetical character from the string str. |
upper() |
It converts lowercase letters in a string to uppercase. |
rstrip() |
It removes all trailing whitespace of a string. |
split(str=””, num=string.count(str)) |
It is used to split strings in Python according to the delimiter str (space if not provided any) and returns the list of substrings in Python |
splitlines( num=string.count(‘n’)) |
It splits a string at the newlines and returns a list of each line with newlines removed. |
This brings us to the end of this module in Python Tutorial. Now, if you are interested in knowing why Python is the most preferred language for data science, you can go through this Python Data Science tutorial.
Moreover, check out our Python Certification Course which will help me excel in my career and reach new heights. Also, avail of the free guide to all the trending Python developer interview questions, created by the industry experts.