Day 2

Strings are Iterables.

In [1]:
#We can iterate through the strings using a for loop.

name = 'syam'
for char in name:
    print(char)
s
y
a
m
In [2]:
#The iteration is case sensitive.

lang = 'MaLAyalAM'
for char in lang:
  if char == 'a':
    print(char)
a
a
In [3]:
#We can check the occurance of a letter(both lower case and upper case) using below code.

lang = 'MaLAyalAM'
for char in lang:
  if char == 'a' or char == 'A':
    print(char)
a
A
a
A
In [4]:
#If we need to check the count. Here as well, its case sentisitive.

lang.count('a')
Out[4]:
2
In [5]:
#To get the exact count

lang.lower().count('a')
Out[5]:
4
In [6]:
#Using count increment.

lang = 'MaLAyaLAM'
count = 0
for char in lang:
  if char.lower() == 'a':
    count = count+1
print(count)
4

Format function to insert variables inside print function.

In [7]:
"Hi {} You are {} years old".format("alex","40")
Out[7]:
'Hi alex You are 40 years old'
In [8]:
lang = 'MaLAyaLAM'
count = 0
for char in lang:
  if char.lower() == 'a':
    count = count+1
print("Total number of A is : {}".format(count))
Total number of A is : 4

List

In [19]:
#A list can be intiated using below

name = []
In [20]:
type(name)
Out[20]:
list
In [21]:
#To add an entry to a list.

#append()

name.append("syam")
name
Out[21]:
['syam']
In [22]:
#A list can have entries with different datatypes.

name.append("mi")
name.append("oneplus")
name.append("samsung")
name.append(1234)
name.append(127.898)
In [23]:
name
Out[23]:
['syam', 'mi', 'oneplus', 'samsung', 1234, 127.898]
In [24]:
#Length of a list can be calculated using len() function.

len(name)
Out[24]:
6
In [26]:
#Indexing works in list.

name[0]
Out[26]:
'syam'
In [27]:
#An item in the list can also be iterated.
name[0][1]
Out[27]:
'y'
In [28]:
#However it is not possible for an integer.

name[4][1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-8a7ab3c9e82f> in <module>
      1 #However it is not possible for an integer.
      2 
----> 3 name[4][1]

TypeError: 'int' object is not subscriptable
In [30]:
name.append("syam")
name
Out[30]:
['syam', 'mi', 'oneplus', 'samsung', 1234, 127.898, 'syam']
In [31]:
#We can find the count of any entry in a list using count function.

name.count('syam')
Out[31]:
2

String Split.

In [33]:
msg = "Amazon Web Services uses information from your Amazon.com account to identify you and allow access to Amazon Web Services." 
In [35]:
#Contents of the string will be converted to a list by split() method.
#By default split() method splits with space as delimeter.

msg.split()
Out[35]:
['Amazon',
 'Web',
 'Services',
 'uses',
 'information',
 'from',
 'your',
 'Amazon.com',
 'account',
 'to',
 'identify',
 'you',
 'and',
 'allow',
 'access',
 'to',
 'Amazon',
 'Web',
 'Services.']
In [36]:
#We can give a delimeter in split function.

"01/12/2019".split("/")
Out[36]:
['01', '12', '2019']
In [38]:
msg.count("Amazon") 
Out[38]:
3
In [41]:
msg.lower().split().count('amazon') #Here the correct occurance will only be taken.
Out[41]:
2
In [42]:
words = msg.lower().split() #Creating a list of words from the string.
for word in words:          #looping through the list
  if word.startswith("a"):   #To find all the words in list which starts with letter 'a'
    print(word)
amazon
amazon.com
account
and
allow
access
amazon
In [43]:
#Fetching the words starting with 'a' and adding them to a list.

result = []
words = msg.lower().split()
for word in words:
  if word.startswith("a"):
    result.append(word)
print(result)  
['amazon', 'amazon.com', 'account', 'and', 'allow', 'access', 'amazon']

List Membership Operation

In [44]:
football = ["messi" , "vijayan" , "ronaldo" , "suarez"]
In [45]:
'messi' in football
Out[45]:
True
In [46]:
'syam' not in football
Out[46]:
True
In [47]:
#We can re write the same code to not include duplicate entries.

result = []
words = msg.lower().split()
for word in words:
  if word.startswith("a"):
    if word not in result:
      result.append(word)
print(result)
['amazon', 'amazon.com', 'account', 'and', 'allow', 'access']

Boolen Values

In [48]:
if 1 == 1:
  print("OK")
OK
In [49]:
if "syam":
  print("OK")
else:
  print("NO")
OK
In [50]:
bool('syam') #Boolean of any value is true(except 0).
Out[50]:
True
In [54]:
bool(1)
Out[54]:
True
In [53]:
bool(0)
Out[53]:
False
In [55]:
bool(None)
Out[55]:
False
In [56]:
bool('')
Out[56]:
False
In [57]:
bool('    ')
Out[57]:
True
In [58]:
if True:
  print("OK")
else:
  print("NO")
OK

Listdir function

In [59]:
import os #To import a module

os.listdir("/etc") #This will print all files/folders inside the given file/folder. Like ls command.
Out[59]:
['lsb-release',
 'default',
 'alternatives',
 'nsswitch.conf',
 'environment',
 '.pwd.lock',
 'systemd',
 'hosts',
 'cron.daily',
 'subgid',
 'init.d',
 'mke2fs.conf',
 'profile.d',
 'issue',
 'legal',
 'selinux',
 'rc6.d',
 'fstab',
 'gshadow',
 'shadow',
 'issue.net',
 'rc2.d',
 'rc1.d',
 'sysctl.conf',
 'opt',
 'securetty',
 'logrotate.d',
 'debian_version',
 'rc3.d',
 'machine-id',
 'pam.d',
 'passwd',
 'sysctl.d',
 'deluser.conf',
 'rc5.d',
 'host.conf',
 'subuid',
 'skel',
 'apt',
 'pam.conf',
 'profile',
 'libaudit.conf',
 'hostname',
 'rcS.d',
 'gai.conf',
 'ld.so.cache',
 'dpkg',
 'resolv.conf',
 'security',
 'adduser.conf',
 'os-release',
 'ld.so.conf',
 'rc0.d',
 'networks',
 'debconf.conf',
 'update-motd.d',
 'terminfo',
 'ld.so.conf.d',
 'shells',
 'rc4.d',
 'login.defs',
 'bindresvport.blacklist',
 'group',
 'bash.bashrc',
 'kernel',
 'rmt',
 'jupyter',
 'mtab',
 'texmf',
 'libpaper.d',
 'papersize',
 'ghostscript',
 'fonts',
 'mailcap',
 'gshadow-',
 'subuid-',
 'shadow-',
 'passwd-',
 'subgid-',
 'group-',
 'locale.gen',
 'locale.alias',
 'mysql',
 'magic',
 'magic.mime',
 'python3.6',
 'X11',
 'ImageMagick-6',
 'python3',
 'emacs',
 'python2.7',
 'mime.types',
 'ssh',
 'mercurial',
 'mailcap.order',
 'python',
 'perl',
 'subversion',
 'ucf.conf',
 'bash_completion.d',
 'logcheck',
 'inputrc',
 'gss',
 'protocols',
 'ssl',
 'rpc',
 'ca-certificates',
 'network',
 'wgetrc',
 'services',
 'ldap',
 'ca-certificates.conf']
In [60]:
#endswith() can be used to check if a string ends with a specific value.

for item in os.listdir("/etc"):
  if item.endswith(".conf"):
    print(item)
nsswitch.conf
mke2fs.conf
sysctl.conf
deluser.conf
host.conf
pam.conf
libaudit.conf
gai.conf
resolv.conf
adduser.conf
ld.so.conf
debconf.conf
ucf.conf
ca-certificates.conf

Absolute Path

In [61]:
import os

os.path.join("syam" , "test")   #This is used to create file locations names in Python.
Out[61]:
'syam/test'
In [63]:
os.path.join("/etc" , "httpd" , "conf" , "httpd.conf")
Out[63]:
'/etc/httpd/conf/httpd.conf'
In [64]:
#To check for every conf file inside /etc and print its absolute path.

for item in os.listdir("/etc"):
  abs_path = os.path.join("/etc" , item)
  if abs_path.endswith(".conf"):
    print(abs_path)
/etc/nsswitch.conf
/etc/mke2fs.conf
/etc/sysctl.conf
/etc/deluser.conf
/etc/host.conf
/etc/pam.conf
/etc/libaudit.conf
/etc/gai.conf
/etc/resolv.conf
/etc/adduser.conf
/etc/ld.so.conf
/etc/debconf.conf
/etc/ucf.conf
/etc/ca-certificates.conf

os.path.getsize() - to get the size of files

In [65]:
#To find all conf files inside /etc and print it's size.

for item in os.listdir("/etc"):
  abs_path = os.path.join("/etc", item)
  if abs_path.endswith(".conf"):
    size = os.path.getsize(abs_path)
    print("{} : {}".format(item,size))
nsswitch.conf : 497
mke2fs.conf : 812
sysctl.conf : 2683
deluser.conf : 604
host.conf : 92
pam.conf : 552
libaudit.conf : 191
gai.conf : 2584
resolv.conf : 141
adduser.conf : 3028
ld.so.conf : 34
debconf.conf : 2969
ucf.conf : 1260
ca-certificates.conf : 5898
In [ ]:
 
In [ ]: