Python String Basics and Formatting Guide
Python String Basics and Formatting Guide
In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have
a character data type, a single character is simply a string with a length of 1. Square brackets can be
used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee
Updation of a character:
# Python Program to Update character of a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a character of the String
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)
Error:
Traceback (most recent call last):
File “/home/[Link]”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deletion of a character:
# Python Program to Delete
# characters from a String
# Deleting a character
# of the String
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)
Error:
Traceback (most recent call last):
File “/home/[Link]”, line 10, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion
Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and
escape sequences inside it are to be ignored.
Output:
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very versatile and
powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders
which can hold arguments according to position or keyword to specify the order.
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Output:
Print String in default order:
Geeks For Life
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
Output:
Binary representation of 16 is
10000
one-sixth is :
0.17
A string can be left() or center(^) justified with the use of format specifiers, separated by a colon(:).
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks', 'for', 'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|
Old style formatting was done without the use of format method by using % operator
String constants
Built-In Function Description
string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants.
string.ascii_lowercase Concatenation of lowercase letters
string.ascii_uppercase Concatenation of uppercase letters
[Link] Digit in strings
[Link] Hexadigit in strings
[Link] concatenation of the strings lowercase and uppercase
[Link] A string must contain lowercase letters.
[Link] Octadigit in a string
[Link] ASCII characters having punctuation characters.
[Link] String of characters which are printable
[Link]() Returns True if string ends with given suffix otherwise returns False
[Link]() Returns True if string starts with given prefix otherwise returns False
[Link]() Returns True if all characters in string are digits, Otherwise, returns False
[Link]() Returns True if all characters in string are alphabets, Otherwise, returns False
[Link]() Returns true if all characters in a string are decimal.
[Link]() one of the string formatting methods, which allows multiple substitutions
and value formatting.
[Link] Returns the position of the first occurrence of substring in a string
[Link] A string must contain uppercase letters.
[Link] A string containing all characters that are considered whitespace.
[Link]() Method converts all uppercase characters to lowercase and vice versa
of the given string, and returns it
replace() returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Deprecated string functions
import module
When interpreter encounters an import statement, it imports module if the module is present in search
path. A search path is a list of directories that the interpreter searches for importing a module. For
example, to import the module [Link], we need to put the following command at the top of the script.
Note: This does not import the functions or classes directly instead imports the module only. To access
the functions inside the module the dot(.) operator is used.
print([Link](10, 2))
Output:
12
The from import Statement
Python’s from statement lets you import specific attributes from a module without importing the
module as a whole.
Output:
4.0
720
Import all Names – From import * Statement
The * symbol used with the from import statement is used to import all the names from a module to a
current namespace.
Syntax:
Output
4.0
720
Locating Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it will check
for the built-in module, if not found then it looks for a list of directories defined in the [Link]. Python
interpreter searches for the module in the following manner –
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then searches each directory in the shell
variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of
directories.
If that also fails python checks the installation-dependent list of directories configured at the time
Python is installed.
Example: Directories List for Modules
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/[Link]’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-
dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’,
‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
Output
4.0
720
The dir() function
The dir() built-in function returns a sorted list of strings containing the names defined by a module. The
list contains the names of all the modules, variables, and functions that are defined in a module.
Output:
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’,
‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’,
‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_acos’,
‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’,
‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’,
‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’,
‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’,
‘vonmisesvariate’, ‘weibullvariate’]
# Sine of 2 radians
print([Link](2))
# 1 * 2 * 3 * 4 = 24
print([Link](4))
# using choice function in random module for choosing a random element from a set such as
a list
print([Link](List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the Unix Epoch, January 1st 1970
print([Link]())
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06
# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
Output:
2
As stated above random module creates pseudo-random numbers. Random numbers depend on
seeding value. For example, if seeding value is 5 then output of below program will always be the same.
Example: Creating random numbers with seeding value
import random
[Link](5)
print([Link]())
print([Link]())
Output:
0.6229016948897019
0.7417869892607294
The output of the above code will always be the same. Therefore, it must not be used for encryption.
Let’s discuss some common operations performed by this module.
Output:
Random number between 5 and 15 is 7
Random number between -10 and -2 is -9
Creating Random Floats
[Link]() method is used to generate random integers between 0.0 to 1.
Syntax:
[Link]()
# import random
from random import random
Output:
0.3717933555623072
# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
# prints a random item from the string
string = "geeks"
print([Link](string))
# prints a random item from the tuple
tuple1 = (1, 2, 3, 4, 5)
print([Link](tuple1))
Output:
2
k
5
Shuffling List
[Link]() method is used to shuffle a sequence (list). Shuffling means changing the position of
the elements of the sequence. Here, the shuffling operation is inplace.
Syntax:
[Link](sequence, function)
Example: Shuffling a List
Output:
Original list :
[1, 2, 3, 4, 5]
After the first shuffle :
[4, 3, 5, 2, 1]
After the second shuffle :
[1, 3, 4, 5, 2]
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is a
package.
3. Then we create another file with the name [Link] and add the similar type of code to it with
different members.
4. Then we create another file with the name [Link] and add the similar type of code to it with
different members.
5. Finally we create the __init__.py file. This file will be placed inside Cars directory and can be left
blank or we can put this initialisation code into it.
6. Now, let’s use the package that we created. To do this make a [Link] file in the same directory
where Cars package is located and add the following code to it:
1. import in Packages
Suppose the cars and the brand directories are packages. For them to be a package they all must
contain __init__.py file in them, either blank or with some initialization code. Let’s assume that
all the models of the cars to be modules. Use of packages helps importing any modules,
individually or whole.
Suppose we want to get Bmw i8. The syntax for that would be:
'import' [Link].x5
While importing a package or sub packages or modules, Python searches the whole tree of
directories looking for the particular package and proceeds systematically as programmed by
the dot operator.
If any module contains a function and we want to import that. For e.g., a8 has a function
get_buy(1) and we want to import that, the syntax would be:
import [Link].a8
[Link].a8.get_buy(1)
While using just the import syntax, one must keep in mind that the last attribute must be a
subpackage or a module, it should not be any function or class name.
2. ‘from…import’ in Packages
Now, whenever we require using such function we would need to write the whole long line after
importing the parent package. To get through this in a simpler way we use ‘from’ keyword. For
this we first need to bring in the module using ‘from’ and ‘import’:
from [Link] import a8
Now we can call the function anywhere using
a8.get_buy(1)
There’s also another way which is less lengthy. We can directly import the function and use it
wherever necessary. First import it using:
from [Link].a8 import get_buy
Now call the function from anywhere:
get_buy(1)
3. ‘from…import *’ in Packages
While using the from…import syntax, we can import anything from submodules to class or
function or variable, defined in the same module. If the mentioned attribute in the import part is
not defined in the package then the compiler throws an ImportError exception.
Importing sub-modules might cause unwanted side-effects that happens while importing sub-
modules explicitly. Thus we can import various modules at a single time using * syntax. The
syntax is:
Syntax :
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
# Child class inheriting Parent class
class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class
...
...
Example :
# parent class
class Parent:
class Component:
class Composite:
Output
Component class object created...
Composite class object also created...
Composite class m2() method executed...
Component class m1() method executed...
Explanation:
In the above example, we created two classes Composite and Component to show the Has-A
Relation among them.
In the Component class, we have one constructor and an instance method m1().
Similarly, in Composite class, we have one constructor in which we created an object of Component
Class. Whenever we create an object of Composite Class, the object of the Component
class is automatically created.
Now in m2() method of Composite class we are calling m1() method of Component Class using
instance variable obj1 in which reference of Component Class is stored.
Now, whenever we call m2() method of Composite Class, automatically m1() method of Component
Class will be called.
Composition vs Inheritance
It’s big confusing among most of the people that both the concepts are pointing to Code
Reusability then what is the difference b/w Inheritance and Composition and when to use Inheritance
and when to use Composition?
Inheritance is used where a class wants to derive the nature of parent class and then modify or extend
the functionality of it. Inheritance will extend the functionality with extra features allows overriding of
methods, but in the case of Composition, we can only use that class we can not modify or extend the
functionality of it. It will not provide extra features. Thus, when one needs to use the class as it without
any modification, the composition is recommended and when one needs to change the behavior of the
method in another class, then inheritance is recommended.
File Handling:
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning
of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a
new file for writing.
6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading
and writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −
[Link]. Attribute & Description
1 [Link]
Returns true if file is closed, false otherwise.
2 [Link]
Returns access mode with which file was opened.
3 [Link]
Returns name of the file.
4 [Link]
Returns false if space explicitly required with print, true otherwise.
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
print "Closed or not : ", [Link]
print "Opening mode : ", [Link]
print "Softspace flag : ", [Link]
This produces the following result −
Name of the file: [Link]
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object, after
which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a
good practice to use the close() method to close a file.
Syntax
[Link]()
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
# Open a file
fo = open("[Link]", "wb")
[Link]( "Python is a great language.\nYeah its great!!\n")
# Open a file
fo = open("[Link]", "r+")
str = [Link](10);
print "Read String is : ", str
# Close opend file
[Link]()
This produces the following result −
Read String is : Python is
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write
will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the
current position as the reference position and if it is set to 2 then the end of the file would be taken as
the reference position.
Example
Let us take a file [Link], which we created above.
#!/usr/bin/python
# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print "Read String is : ", str