Unit 5
Unit 5
s='Hello' Output:
print(s)
Hello
s= "Hello" Hello
print(s) Hello
Hello, welcome to
s = '''Hello''' the world of Python
print(s)
s = """Hello, welcome to
the world of Python"""
print(s)
String Operation
Create list of strings
To create a list of strings, first use square brackets [ ] to create a list.
Then place the list items inside the brackets separated by commas.
strings must be surrounded by quotes.
use = to store the list in a variable.
Ex:
colors = ["red", "blue", "green"]
Ex:
colors = [
"red",
"blue",
"green"
]
Print list of strings
To print a whole list of strings in one line, you can simply call the built-in print function,
colors = ["red", "blue", "green"] Output
print(colors) ['red', 'blue', 'green']
If you want to convert a list to a string, you can use the built-in function repr to make a string
representation of the list:
print(type(colors_str))
Concatenate lists of strings
You can use the + operator to concatenate two lists of strings. For example:
print(color)
Check if string is in list
print("yes!") True
print(ans)
To join a list of strings by another string, you need to call the join method on the string, giving your
list as an argument. For example, if we have this list:
colors = ["red", "white","blue"] Output:
print("".join(colors)) redwhiteblue
print(" ".join(colors)) red white blue
print("|".join(colors)) red|white|blue
5.2 Access String elements using index operator
You can use a for loop,range in python and slicing operator to traverse a character in a string.
Using for loop to traverse a string
str="python" Output:
for s in str: p
print(s) y
t
h
o
n
Using range to traverse a string:
str="python" Output:
for s in range(len(str)): p
print(str[s]) y
t
h
o
n
Using slicing operator to traverse a string partially
A segment of a string is called a slice.
Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
Slice out substrings, sub lists, sub Tuples using index.
str="Python" Output
l=len(str)-1 n
while l>=0: o
print(str[l]) h
l=l-1 t
y
p
● Testing functions: isalnum, isalpha, isdigit, isidentifier, islower, isupper, and isspace
isalnum(): returns True if all the characters in the string is alphanumeric (a string which contains
either number or alphabets or both). Otherwise return False
s=" " Output:
print(s.isalnum()) False
s="abc" True
print(s.isalnum()) True
s='123' True
print(s.isalnum()) False
s='abc123' False
print(s.isalnum())
s='+-'
print(s.isalnum())
s='a b'
print(s.isalnum())
isupper: returns True if all the characters in the string are in uppercase. Otherwise return False.
s = 'PYthon' Output:
print(s.isupper()) False
print("ABC".isupper()) True
isspace : returns True if all the characters in the string are whitespace characters. Otherwise return
False.
print("\n\t".isspace()) Output:
print(" \n\t".isspace()) True
print("@ \n\t".isspace()) True
print("123".isspace()) False
False
● Manipulation functions:
capitalize( ): It returns a copy of the original string and converts the first character of the string to a
capital (uppercase) letter, while making all other characters in the string lowercase letters.
Syntax: string_name.capitalize()
s= "hello world" Output:
print(s.capitalize()) Hello world
print("heLLo".capitalize()) Hello
print('123'.capitalize()) 123
lower( ): This function converts all uppercase characters in a string into lowercase characters and
returns it.
Syntax: string.lower()
s= "HEllo" Output:
print("Original string:",s) Original string: HEllo
print("Converted string:"+s.lower()) Converted string:hello
upper ( ): This function converts all lowercase characters in a string into uppercase characters and
returns it.
Syntax: string.upper()
s= "HEllo" Output:
print("Original string:",s) Original string: HEllo
print("Converted string:"+s.upper()) Converted string:HELLO
title ( ): It converts the first character in each word to uppercase and the remaining characters to
lowercase in the string and returns a new string.
Syntax: string.title()
s= "hELLo good morning" Output:
print("Original string:",s) Original string: hELLo good morning
print("Converted string:"+s.title()) Converted string:Hello Good Morning
swapcase: The string swapcase() method converts all uppercase characters to lowercase and lowercase
characters to uppercase of the given string, and returns it.
Syntax: string.rstrip([characters])
Parameters: characters (optional) – a string specifying the set of characters to be removed.
s="Hello " Output:
print(s.rstrip()) Hello
s="Hello+..+&.." Hello
print(s.rstrip('.+&'))
strip: It is an inbuilt function in the Python programming language that returns a copy of the string
with both leading and trailing characters removed.
Syntax: string.strip([characters])
s=" Hello World..." Output:
print(s) Hello World...
print(s.strip()) Hello World...
print(s.strip('.')) Hello World
casefold: Python String casefold() method is used to convert string to lower case. It is similar to
lower() string method, but case removes all the case distinctions present in a string.
For example, the German letter ß is already lowercase so, the lower() method doesn't make the
conversion.
But the casefold() method will convert ß to its equivalent character ss.
Syntax: string.casefold()
s="HELLO" Output:
● Formatting functions:
format: The format() method formats the specified value(s) and insert them inside the string's
placeholder. The placeholder is defined using curly brackets: {}. It is used for handling complex string
formatting more efficiently.
Syntax: string.format(value1, value2...)
a=5 Output:
b=10 5+10=15
s='{0}+{1}={2}'.format(a,b,a+b)
print(s)
a=5 Output:
s='{0}**{1}={2}'.format(a,2,a**2) 5**2=25
print(s)
s="My name is {fname}".format(fname = "abc") Output:
print(s) My name is abc
center: It creates and returns a new string that is padded with the specified character.
Syntax: string.center(length[, fillchar])
length: length of the string after padding with the characters.
fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as
the default argument.
s="Hello World" Output:
print(s.center(20)) Hello World
print(s.center(5)) Hello World
print(s.center(20,"#")) ####Hello World#####
print(s.center(5,"#")) Hello World
ljust: This method left aligns the string according to the width specified and fills the remaining space
of the line with blank space if ‘fillchr‘ argument is not passed.
rjust: This method left aligns the string according to the width specified and fills the remaining space
of the line with blank space if ‘fillchr‘ argument is not passed.
Syntax: rjust(len, fillchr)
len: The width of string to expand it.
fillchr (optional): The character to fill in the remaining space.
s = "hello" Output:
print(s.rjust(10)) hello
Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.
Files
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file, we need to open it first.
When we are done, it needs to be closed so that the resources that are tied with the file are freed.
In Python, a file operation takes place in the following order:
Open a file
Read or write (perform operation)
Close the file
read( ) : Returns the read bytes in form of a string. It reads n bytes, if no n specified, reads the entire
file.
Syntax: File object.read([n])
f=open("a.txt","r") Output:
print(f.read( )) hello everyone
f.close() Good morning
f=open("a.txt","r") Output:
print(f.read(14)) hello everyone
f.close()
readline( ) : Reads a line of the file and returns in form of a string. For specified n, reads at most n
bytes. It does not reads more than one line.
Syntax: File object.readline([n])
f=open("a.txt","r") Output:
print(f.read(5)) hello
f.close()
f=open("a.txt","r") Output:
print(f.readline()) hello everyone
f.close()
Readlines( ): Reads all the lines and return them as each line a string element in a list.
Syntax: File_object.readlines()
f=open("a.txt","r") Output:
print(f.readlines( )) ['hello everyone\n', 'Good morning\n', 'Have a nice day\n']
f.close()