Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Python

The document discusses various string operations in Python like traversing a string using a while loop, accessing characters using indexes and slices, and using string methods like upper(), lower(), count(), find(), etc. It also discusses changing the current working directory and creating new directories in Python using functions like os.chdir() and os.makedirs() from the os module.

Uploaded by

n3004dsouza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python

The document discusses various string operations in Python like traversing a string using a while loop, accessing characters using indexes and slices, and using string methods like upper(), lower(), count(), find(), etc. It also discusses changing the current working directory and creating new directories in Python using functions like os.chdir() and os.makedirs() from the os module.

Uploaded by

n3004dsouza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

i.

Append: append adds a new element to the end of a list:


>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
ii. Extend: extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
iii. Sort: sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
iv. index: >>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
v. The remove() method is passed the value to be removed from the list it is called
on
>>>spam=[‘cat’,’bat’,’rat’,’elephant’]
>>>spam.remove(‘bat’)
>>>spam
[‘cat’,’rat’,’elephant’]

Just like how str(42) will return '42', the string representation of the integer 42, the functions list()
and tuple() will return list and tuple versions of the values passed to them. Enter the following
into the interactive shell, and notice that the return value is of a different data type than the
value passed:
>>> type(('hello',))
<class'tuple'>
>>> type(('hello'))
<class 'str'>
Using a loop
This method is similar to the above one, but in this case, we do not send the
complete list as an argument whereas we retrieve each element from the list
using a for loop to send it as an argument for the tuple() built-in function.
Example
The following is an example code to convert a list to a tuple using a loop.
list_names=['Meredith', 'Kristen', 'Wright', 'Franklin']
tuple_names= tuple(i for i in list_names)
print(tuple_names)
print(type(tuple_names))
Output
('Meredith', 'Kristen', 'Wright', 'Franklin')
<class 'tuple'>

i)# Initialization of dictionary


dict = {'Geeks': 10, 'for': 12, 'Geek': 31}
# Converting into list of tuple
list = [(k, v) for k, v in dict.items()]
# Printing list of tuple
print(list)
Output:
[('Geek', 31), ('for', 12), ('Geeks', 10)]
ii) # Initializing list
list_tuple = [('Pytho', '35ddays', 2000), ('Spark', '40days'
,2500 ), ('Java', '50days', 3000)]
# Example 1: Using list comprehension
# Tuple as dictionary key
result = {(sub[0], sub[1]): sub[2:] for sub in list_tuple}
print("Dictionary after conversion : ", result)
import os.path
import sys
fname = input("Enter the filename whose contents are to be sorted : ")
#sample file Text.txt also provided
if not os.path.isfile(fname):
print("File", fname, "doesn’t exists")
sys.exit(0)
infile = open(fname, "r")
myList = infile.readlines()
lineList = []
for line in myList:
lineList.append(line.strip())
lineList.sort()
outfile = open("sorted.txt","w")
for line in lineList:
outfile.write(line + "\n")
infile.close() # Close the input file
outfile.close() # Close the output file
if os.path.isfile("sorted.txt"):
print("\nFile containing sorted content sorted.txt created
successfully")
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")
print("============================================
==============")
rdFile = open("sorted.txt","r")
for line in rdFile:
print(line, end="")

String is a collection of alphabets, words or other characters. It is one of the primitive


data structures and are the building blocks for data manipulation. Python has a builtin string
class named str .
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
This loop traverses the string and displays each letter on a line by itself. The
loop condition is index < len(fruit), so when index is equal to the length of the
string, the condition is false, and the body of the loop is not executed. The last
character accessed is the one with the index len(fruit)-1, which is the last
character in the string.
Strings use indexes and slices the same way lists do. You can think of the
string 'Hello, world!' as a list and each character in the string as an item with a
corresponding index.
'Hello,world!'
0 1 2 3 4 5 6 7 8 9 10 11 12
The space and exclamation point are included in the character count, so 'Hello,
world!' is 13 characters long, from H at index 0 to ! at index 12.

change directory by using the following function os.chdir().


b.get the current working directory as a string value with the Path.cwd() function and
from pathlib import Path
>>> import os
>>> Path.cwd()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')'
>>> os.chdir('C:\\Windows\\System32')
2+2
>>> Path.cwd()
WindowsPath('C:/Windows/System32')
c. create new folders (directories) with the os.makedirs() function. Enter the
following into the interactive shell:
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles’)

You might also like