String Datatype in Python

Python string is an ordered collection of characters which is used to represent and store the text-based information. Strings are stored as individual characters in a contiguous memory location. It can be accessed from both the directions in forward and backward. Characters are nothing but symbols. Python Strings are immutable Datatypes in Python, which means that once a string is created, they cannot be changed. In this module you will learn all about Strings in Python so as to get started with strings. Following is the list of all the topics that we will cover in this module, in case you want to jump to a specific one.

So, without any further ado, let’s get started.

Learn Python in 16 hrs from experts

Creating Strings in Python

In Python, Strings are created using either single quotes or double quotes. You 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 print () method as shown in the above example. The output of the above example will be as follows:

Intellipaat
Python Tutorial

Accessing String Characters

In Python, the characters of string can be individually accessed using a method called indexing. The characters can be accessed from both the directions in forward and backward. Forward indexing start form 0,1,2.. and so on Whereas backward indexing start form -1, -2, -3.. and so on, where -1 is the last element in a string and -2 is the second last and so on. We can only use 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

Wish to Learn Python? Click Here

Updating or deleting Strings

As discussed above, Strings in Python are immutable and thus updating or deleting an individual character in a String is not allowed, that means, changing a particular character in 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

Become Python Certified in 16 hrs.

X

String operators

There are 3 types of operators are supported by the string which are –

  • Basic Operators(+, *)
  • Relational Operators(<, ><=, >=, ==, !=)
  • Membership Operators(in, not in)

Table: Common String Constants and Operations

OperatorsDescription
s1 = ‘  ’Empty string
s2 = “a string”Double quotes
block = ‘‘‘…’’’Triple-quoted blocks
s1 + s2Concatenate
s2 * 3repeat
s2[i]i=Index
s2[i:j]slice
len(s2)length
“a %s parrot” % ‘dead’String formatting
for x in s2Iteration
‘m’ in s2membership

Table:  String Backslash Characters

OperatorsDescription
\newlineIgnored (a continuation)
\nNewline (ASCII linefeed)
\\Backslash (keeps one \)
\vVertical tab
\’Single quote (keeps ‘)
\tHorizontal tab
\”Double quote (keeps “)
\rCarriage return
\aASCII bell
\fForm feed
\bBackspace
\0XXOctal value XX
\eEscape (usually)
\xXXHex value XX
\000Null (doesn’t end string)

Example: Program to concatenate two strings.

S1 = “hello”
S2 = “Intellipaat”
print (S1 + S2)

Watch this video on Python string Operation

Built in String methods

Let’s understand all the standard built in String methods in Python through the following table:

MethodDescription
capitalize()It capitalizes the first letter of string
center(width, fillchar)It returns a space-padded string with the original string centered to a total of width columns.
count(str, beg= 0,end=len(string))It counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
encode(encoding=’UTF-8′,errors=’strict’)It returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
endswith(suffix, beg=0, end=len(string))It returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
endswith(suffix, beg=0, end=len(string))It determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8)It expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tab size not provided.
find(str, beg=0 end=len(string))It determines if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string))Works just like find(), but raises an exception if str not found.
isalnum()It returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isalpha()It returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
isdigit()It returns true if string contains only digits and false otherwise.
islower()It returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
isupper()It returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
len(string)It returns the length of the 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 string.
split(str=””, num=string.count(str))Splits string according to delimiter str (space if not provided any), returns list of substrings which are split into at most num substrings if given
splitlines( num=string.count(‘\n’))Splits string at the newlines and returns a list of each line with newlines removed.

This brings us to the end of this module, the next module highlights List Datatype in Python. See you there!

Leave a Reply

Your email address will not be published. Required fields are marked *