Friday, January 15, 2021

String in python

Introduction:

In python strings are character enclosed in quotes of any type i.e. Single quotation marks or double quotation marks.

Note:
  • Strings are immutable i.e. any character inside the string cannot be changed once declared i.e. str[i]='h' is invalid
  • Square brackets can be used to access elements of the string. i.e. str[i]
  • The String are sequence of character, where each character has a unique poistion id/index. The indexs of a string beigns from 0 to (length-1) from left to right and from -1 to -(length) from right to left

Example: "hello", 'hello', "436", "45.69", "[4,5,6]", " ", "today is 1/11/2020"

Traversing a string:

In [2]:
s="Computer"
for i in s:
    print(i)
C
o
m
p
u
t
e
r
In [3]:
s='computer'
for i in range(0,len(s)):
    print(s[i])
c
o
m
p
u
t
e
r

Operation:

Concatenation:

+ operator creates a new string by joining two operand string

In [5]:
s1="Computer"
s2="Science"
final=s1+" "+s2
print(final)
Computer Science

String replication:

* operator is used with a number to replicate the original string

In [6]:
s1="Hello"
final=s1*3
print(final)
HelloHelloHello

Membership operator:

Membership operator is used to check the presence of a string in another string
string1 in string2
string1 not in string2

In [7]:
'ter' in 'Computer'
Out[7]:
True
In [8]:
'ter' not in 'Computer'
Out[8]:
False

Comparison operator:

All realational operator (<,>,<=,>=,!=) can be used with string in python

In [11]:
print('a'=='a')
print('a'>'abc')
print('a'!='a')
print('Abc'>'abc') #in ASCII A=65 and a=97
print('Abc'<='Abc')
True
False
False
False
True
In [14]:
#Note to find ASCII value of a character we can use ord function
print(ord('A'))
print(ord('a'))
65
97

String Slicing:

Slicing is the process of obtaining a substring from the exsisting string

Syntax:
name[starting_index : stop_index : jump_value]

Note: jump_value is optional and by default its 1

In [18]:
sub="Computer Science"
print(sub[2:8])
print(sub[2:8:2])
mputer
mue

String Function/Methods:

string.capitalize():  Converts the first letter of the first word of a string into uppercase

In [20]:
sub="computer"
print(sub.capitalize())
Computer

string.lower():  Converts the string to lower case

In [21]:
sub="COMPUTER"
print(sub.lower())
computer

string.upper():  Converts the string into upper case

In [22]:
sub="computer"
print(sub.upper())
COMPUTER

len(string):  Returns the number of character in the string

In [2]:
sub="computer"
len(sub)
Out[2]:
8

string.title():  it converts first letter of each word in the string into uppercase

In [3]:
sub="computer science"
print(sub.title())
Computer Science

string.count(sub_string):   String count() function returns the number of occurrences of a substring in the given string.

In [4]:
string = "Python is awesome, isn't it?"
substring = "is"
val = string.count(substring)

print(val)
2

string.find(value):  The find() method finds the position of first occurrence of the specified value in a string. Return -1 if not found

In [5]:
sub="Computer Science"
value="ter"
pos=sub.find(value)
print(pos)
5

string.index(value):  The index() method finds the first occurrence of the specified value. The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found and index() function through exception.

In [6]:
sub="Computer Science"
value="ter"
pos=sub.index(value)
print(pos)
5

string.split("separator"):   The split() function splits a string into a list based on the seperator character.

In [7]:
txt="today,is,a,good,day"
ls=txt.split(",")
print(ls)
['today', 'is', 'a', 'good', 'day']

string.partition("sub_string"):  The partition() method searches for a specified string, and splits the string into a tuple containing three elements.

In [9]:
txt="today is good Friday"
ls=txt.partition("is")
print(ls)
('today ', 'is', ' good Friday')

string.strip("character"):   removes spaces(by default) or character from the beginning and end of the string.

In [15]:
txt="  Computer  "
print(txt.strip())
txt=".Computer."
print(txt.strip('.'))
Computer
Computer

string.lstrip():  removes spaces(by default) or character from the beginning of the string.

In [16]:
txt="  Computer  "
print(txt.lstrip())
txt=".Computer."
print(txt.lstrip('.'))
Computer  
Computer.

string.rstrip():  removes spaces(by default) or character from the end of the string.

In [17]:
txt="  Computer  "
print(txt.rstrip())
txt=".Computer."
print(txt.rstrip('.'))
  Computer
.Computer

string.replace(oldvalue, newvalue, count)  The replace() method replaces a specified phrase with another specified phrase.

In [18]:
txt="today is good Friday"
ls=txt.replace("good","very good")
print(ls)
today is very good Friday

string.isalnum():   Return True if the character in the string are alphanumeric(alphabet or number) and there is atleast one character in the string else return False

In [20]:
str1="abc12"
print(str1.isalnum())
str2=""
print(str2.isalnum())
True
False

string.isalpha():   Return True if the character in the string are alphabet and there is atleast one character in the string else return False

In [22]:
str1="abc"
print(str1.isalpha())
str2="abc123"
print(str2.isalpha())
True
False

string.isdigit():   Return True if the character in the string are number and there is atleast one character in the string else return False

In [23]:
str1="12345"
print(str1.isdigit())
str2="abc"
print(str2.isdigit())
True
False

string.islower():   Return True if all the character in the string are in lower case and there is atleast one character in the string else return False

In [25]:
str1="Abc"
print(str1.islower())
str2="abc"
print(str2.islower())
False
True

string.isupper():   Return True if all the character in the string are in upper case and there is atleast one character in the string else return False

In [26]:
str1="ABC"
print(str1.isupper())
str2="Abc"
print(str2.isupper())
True
False

string.isspace():   Return True if there are all whitespace character in the string and there is atleast one character in the string else return False

In [28]:
str1="   "
print(str1.isspace())
str2=""
print(str2.isupper())
True
False

Practice Program:

  1. Write a python program to print a string in reverse order character by character in a new line
  1. Write a program that reads a line and prints its statistics like:
    a. Number of uppercase letter
    b. Number of lowercase letter,
    c. Number of alphabet
    d.Number of digit
    Sample String: "3.14 is the value of PI"
In [ ]:
 
Share:

Saturday, December 12, 2020

Computer Memory

Introduction:

Memory basically means storage media i.e. the hardware on which data is stored. A computer system needs memory to store the data and instruction for processing.

Units Of Memory:

Inorder to measure the amount of data, units of memory are used. A computer system uses binary numbers to store and process data. The binary digits 0 and 1, which are the basic units of memory, are called bits.A bit is smallest unit of memory which can store either a 1 or 0 but not both. Below are the data units

  • 1 bit : stores 1/0
  • 1 nibble: stores 4 bits
  • 1 Byte : stores 8 bits
  • 1 KB(Kilobyte) : 1024 Bytes
  • 1 MB(Megabyte) : 1024 KB
  • 1 GB(Gigabyte) : 1024 MB
  • 1 TB(Terabyte) : 1024 GB
  • 1 PB(Petabyte) : 1024 TB
  • 1 EB(Exabyte) : 1024 PB
  • 1 ZB(Zettabyte) : 1024 EB
  • 1 TB(Yottabyte) : 1024 ZB
NOTE: In 2020 the total amount of digital data is about 40 ZB

Types of memory:

On the basis of distance from the CPU and speed of the memory device, memory can be classified into 3 types (1) cache memory (2) primary memory (3) secondary memory

cache memory:

cache memory is usually small memory present on the CPU die. cache is very fast as compared to RAM but of very samll size, typically of 1-3mb. only a part of data/program is loaded into the cache for faster access by the microprocessor.

Primary memory:

primary memory means the RAM/ROM which is placed after cache memory is not present on the CPU but on the motherboard. Program and data are loaded into the primary memory before processing. The CPU interacts directly with the primary memory to perform read or write operation. It is of two types viz. (i) Random Access Memory (RAM) and (ii) Read Only Memory (ROM).

RAM is volatile, i.e., as long as the power is supplied to the computer, it retains the data in it. But as soon as the power supply is turned off, all the contents of RAM are wiped out. It is used to store data temporarily while the computer is working. Whenever the computer is started or a software application is launched, the required program and data are loaded into RAM for processing. RAM is usually referred to as main memory

ROM is non-volatile, which means its contents are not lost even when the power is turned off. It is used as a small but faster permanent storage for the contents which are rarely changed. For example, the startup program (boot loader) that loads the operating system into primary memory, is stored in ROM.

Secondary memory:

Primary memory has limited storage capacity and is either volatile (RAM) or read-only (ROM). Thus, a computer system needs auxiliary or secondary memory to permanently store the data or instructions for future use. The secondary memory is non-volatile and has larger storage capacity than primary memory. It is slower and cheaper than the main memory. But, it cannot be accessed directly by the CPU. Contents of secondary storage need to be first brought into the main memory for the CPU to access. Examples of secondary memory devices include Hard Disk Drive (HDD), CD/DVD, Memory Card, etc.

Data Capture, Storage and Retrieval:

Computers are good at data processing, inorder to do this the data is to be obtained/captured from external sources, stored into some file or database and when the data is to be processed, then it has to be retrived from the file or database

(A) Data Capturing:

It involves the process of gathering data from different sources in digital form. Some of the possible ways are:

  • using barcode scanner get the information about the product
  • using keyboard
  • using camera sensor to get an image

(B) Data Storage:

After the data is captured through devices/sensors, they are stored on storage medium like HDD, DVD, prndrive etc. the data stored are some sort of representation of binary i.e. 0/1

(c) Data Retrieval:

It involves fetching data from the storage devices, for its processing as per the user requirement.Minimising data access time is crucial for faster data processing.

Data Deletion and Recovery:

deletion of data means that data becomes inaccesible to the user.Deleting digitally stored data means changing the details of data at bit level, which can be very timeconsuming. Therefore, when any data is simply deleted, its address entry is marked as free, and that much space is shown as empty to the user, without actually deleting the data.

Recovery of the data is possible only if the contents/memory space marked as deleted have not been overwritten by some other data. Data recovery is a process of retrieving deleted, corrupted and lost data from secondary storage devices.

There are two security concerns associated with data

  • One is its deletion by some unauthorised person or software. These concerns can be avoided by limiting access to the computer system and using passwords for user accounts and files, wherever possible. There is also an option of encrypting files to protect them from unwanted modification.
  • The other concern is related to unwanted recovery of data by unauthorised user/software. This concern can be mitigated by using proper tools to delete or shred data before disposing off any old or faulty storage device. Example of software to permanently delete data (1) WipeFile, (2) HardWipe etc

Refernces:

  1. NCERT for Class 11
Share: