Python String
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this
section of the tutorial, we will discuss the most popular data type in Python, i.e.,
string.
Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
Syntax:
str = "Hi Python !"
print (str)
Like other languages, the indexing of the Python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
Output:
H
E
L
L
O
EXAMPLE -2 INDEXING
str = "CAMBRIDGE"
print(str[0:])
print(str[1:5])
print(str[2:4])
print(str[:3])
print(str[4:7])
3 .. EXAMPLE – 3 -VALUE
str = 'CAMBRIDGE'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
print(str[::-1])
print(str[-12])
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The
string object doesn't support item assignment i.e., A string can only be replaced
with new string since its content cannot be partially replaced. Strings are
immutable in Python.
str = "HELLO"
print(str)
str = "hello"
print(str)
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.
str1 = "INDIA"
del str1
print(str1)
---------------------------------- string use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10.print("The string str : %s"%(str)) # prints The string str : Hello
Operato Description
r
[:] It is known as range slice operator. It is used to access the characters from
the specified range.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where
we need to print the actual meaning of escape characters such as
"C://python". To define any string as a raw string, the character r or R is
followed by the string.
Let's suppose we need to write the text as - They said, "Hello what's going on?"-
the given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.
We can ignore the escape sequence from the given string by using the raw string.
We can do this by writing r or R in front of the string. Consider the following
example.
print(r"C:\\Users\\balaji\\Python32")
The format() method is the most flexible and useful method in formatting strings.
The curly braces {} are used as the placeholder in the string and replaced by
the format() method argument. Let's have a look at the given an example:
Python allows us to use the format specifiers used in C's printf statement. The
format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an interface
between the format specifiers and their values. In other words, we can say that it
binds the format specifiers to the values.
example.
Integer = 10;
Float = 1.290
String = "Krishna"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I a
m string ... My value is %s"%(Integer,Float,String))
How String slicing in Python works
For understanding slicing we will use different methods, here we will cover 2
methods of string slicing, one using the in-build slice() method and another using
the [:] array slice. String slicing in Python is about obtaining a sub-string from
the given string by slicing it respectively from start to end.
# String slicing
String = 'ASTRING'
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Method 2: Using the List/array slicing [ :: ] method
In Python, indexing syntax can be used as a substitute for the slice object. This is
an easy and convenient way to slice a string using list slicing and Array slicing
both syntax-wise and execution-wise. A start, end, and step have the same
mechanism as the slice() constructor.
Below we will see string slicing in Python with examples.
EX : -2
# String slicing
String = 'CAMBRIDGE'
EX : 3
String = 'CAMBRIDGE COLLEGE'
--
Reverse a String
You can reverse a string by omitting both start and stop indices and specifying
a step as -1.
S='ABCDEFGHI'
print(S[::-1]) # I H G F E D C B A
------------SPLIT WORED
s1=’A B C D E F ‘
Print(s1.split(‘ ‘,3)
S2 =Hi@hI@HI@hi@hi”
Print(s2.split(‘@’,2)
We can also do other useful operations on returned list i.e. combining it into a
single string.
Code:
s1 = 'One#Two#Three#Four#Five'
a = s1.split('#')
print(a)
print(len(a))
print(''.join(a))
Python file handling. Python supports the file-handling process. Till now, we were
taking the input from the console and writing it back to the console to interact with
the user. Users can easily handle the files, like read and write the files in Python.
Each line of code includes a sequence of characters, and they form a text file.
Each line of a file is terminated with a special character, called the EOL or End
of Line characters like comma {,} or newline character.
Just like reading a file in Python, there are a number of ways to Writing to file in
Python. Let us see how we can write the content of a file using the write()
function in Python.
file = open(file2.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Opening a File
A file operation starts with the file opening. At first, open the File then Python will
start the operation. File opening is done with the open() function in Python. This
function will accepts two arguments, file name and access mode in which the file is
accessed. When we use the open() function, that time we must be specified the
mode for which the File is opening. The function returns a file object which can be
used to perform various operations like reading, writing, etc.
Syntax:
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Read a file
There is more than one way to How to read from a file in Python . Let us see how
we can read the content of a file in read mode.
file = open(file2.txt', 'r')
for each in file:
print (each)
print(data)
Python Constructor
A constructor is a special type of method (function) which is
used to initialize the instance members of the class.
Constructors can be of two types.
Parameterized Constructor
The parameterized constructor has multiple parameters along
with the self.
Non-parameterized Constructor
The non-parameterized constructor uses when we do not want to
manipulate the value or the constructor that has only self as an
argument
Constructor definition is executed when we create the object of
this class. Constructors also verify that there are enough
resources for the object to perform any start-up task.
• Creating the constructor in python
• In Python, the method the __init__() simulates the
constructor of the class. This method is called when the
class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method
of the class.
EX : 1
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Ex: 2
class Person:
def __init__(self):
self.name = "krishna"
self.gender = "Male"
self.age = 22
def talk(self):
print("Hi I'm ", self.name)
def vote(self):
if self.age<18:
print("I am not eligible to vote")
else:
print("I am eligible to vote")
obj = Person() # creating objects
obj.talk()
obj.vote()