Practicing Coding Interview Questions in Python
Kirill Smirnov
Data Science Consultant, Altran
Create strings:
s = 'hello'
print(s)
hello
s = "hello"
print(s)
hello
str()
constructor:
str("hello")
'hello'
str(11.5)
'11.5'
str([1, 2, 3])
'[1, 2, 3]'
class NewClass:
def __init__(self, num): self.num = num
nc = NewClass(2)
print(nc.num)
2
str(nc)
'<__main__.NewClass instance at 0x105cdabd8>'
class NewClass:
def __init__(self, num): self.num = num
def __str__(self): return str(self.num)
nc = NewClass(3)
str(nc)
'3'
s = "interview"
s[1]
'n'
s[-2]
'e'
s[1:4]
'nte'
s[2:]
'terview'
s[:3]
'int'
s = "interview"
s.index('n')
1
s.index('i')
0
s[0] = 'a'
TypeError
.capitalize()
.lower()
.upper()
.replace()
Methods return a new string object
# String concatencation
s1 = "worm"
s2 = s1 + "hole"
print(s2)
wormhole
# Replace a substring
s1 = 'a dog ate my food'
s2 = s1.replace('dog', 'cat')
print(s2)
a cat ate my food
# Upper case
s3 = s2.upper()
print(s3)
A CAT ATE MY FOOD
# Lower case
s4 = s3.lower()
print(s4)
a cat ate my food
# Capitalization
s5 = s4.capitalize()
print(s5)
A cat ate my food
Create a string from a list of strings:
l = ['I', 'like', 'to', 'study']
s = ' '.join(l) print(s)
I like to study
Breaking a string into a list of strings:
l = s.split(' ')
print(l)
['I', 'like', 'to', 'study']
import pandas as pd
d = {'name': ['john', 'amanda', 'rick'], 'age': [35, 29, 19]}
D = pd.DataFrame(d)
print(D)
name age
0 john 35
1 amanda 29
2 rick 19
D['name'] = # we will modify this column
D['name'] = D['name']
D['name'] = D['name'].str
D['name'] = D['name'].str.capitalize()
print(D)
name age
0 John 35
1 Amanda 29
2 Rick 19
Practicing Coding Interview Questions in Python