0% found this document useful (0 votes)
31 views13 pages

Python String

This document discusses Python strings. It begins by explaining that strings are collections of characters surrounded by quotes. Internally, strings are stored as combinations of 0s and 1s and each character is encoded in ASCII or Unicode. There are several ways to create strings in Python including single quotes, double quotes, and triple quotes. Strings can be indexed and sliced similar to other sequences. Strings are immutable, so their content cannot be modified but they can be reassigned. Various string operators and formatting are also discussed.

Uploaded by

R Sabarish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
31 views13 pages

Python String

This document discusses Python strings. It begins by explaining that strings are collections of characters surrounded by quotes. Internally, strings are stored as combinations of 0s and 1s and each character is encoded in ASCII or Unicode. There are several ways to create strings in Python including single quotes, double quotes, and triple quotes. Strings can be indexed and sliced similar to other sequences. Strings are immutable, so their content cannot be modified but they can be reassigned. Various string operators and formatting are also discussed.

Uploaded by

R Sabarish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

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.

Python string is the collection of the characters surrounded by single quotes,


double quotes, or triple quotes. The computer does not understand the characters;
internally, it stores manipulated character as the combination of the 0's and 1's.

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.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes, or
triple quotes to create the string.

Syntax:
str = "Hi Python !"
print (str)

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double-


quotes. Python also provides triple-quotes to represent the string, but it is generally
used for multiline string or docstrings.

str1 = 'Hello Python'


print(str1)
str2 = "Hello Python"
print(str2)
Strings indexing and splitting

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 concatenation operator used to join the strings given either


side of the operator.

* It is known as repetition operator. It concatenates the multiple copies of


the same string.

[] It is known as slice operator. It is used to access the sub-strings of a


particular string.

[:] It is known as range slice operator. It is used to access the characters from
the specified range.

In It is known as membership operator. It returns if a particular sub-string is


present in the specified string.

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.

% It is used to perform string formatting. It makes use of the format


specifiers used in C programming like %d or %f to map their values in
python. We will discuss how formatting is done in python.
Python String Formatting
Escape Sequence

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.

print('''''They said, "What's there?"''')


print('They said, "What\'s going on?"')
print("They said, \"What's going on?\"")

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

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:

# Using Curly braces


print("{} and {} both are the best friend".format("rama","krishna"))

print("{1} and {0} best players ".format("Virat","Rohit"))

print("{a},{b},{c}".format(a = "latha", b = "sri", c = "gayathri"))

Python String Formatting Using % Operator

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.

Python slicing can be done in two ways:

 Using a slice() method


 Using the array slicing [:: ] method

# Python program to demonstrate


# string slicing

# String slicing
String = 'ASTRING'

# Using slice constructor


s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

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.

# Using indexing sequence


String = 'GEEKSFORGEEKS'
print(String[:3])

EX : -2

# Python program to demonstrate


# string slicing

# String slicing
String = 'CAMBRIDGE'

# Using indexing sequence


print(String[1:5:2])

EX : 3
String = 'CAMBRIDGE COLLEGE'

# Using indexing sequence


print(String[-1:-12:-2])

--
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)

Example 2: Combining the Returned Array.

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))

File Handling in Python

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.

Advantages of File Handling in Python


 Versatility: File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and
deleting files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files, etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling,
making it easy to create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different
platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and
compatibility.
Disadvantages of File Handling in Python
 Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially
if the program accepts user input that can be used to access or modify
sensitive files on the system.
 Complexity: File handling in Python can be complex, especially when
working with more advanced file formats or operations. Careful attention must
be paid to the code to ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or
performing complex operations.

Creating a File using the write() Function

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")

using WITH IN file handling

with open(test1.txt', 'w') as file2:


file2.write('Hello coders')
fil2.write('Welcome to javaTpoint')

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)

using WITH IN file handling

with open("file2.txt") as file:


data = file.read()

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()

You might also like