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: