What are common ways to manipulate strings?

Practicing Coding Interview Questions in Python

Kirill Smirnov

Data Science Consultant, Altran

String

Create strings:

s = 'hello'
print(s)
hello
s = "hello"
print(s)
hello
Practicing Coding Interview Questions in Python

String

str() constructor:

str("hello")
'hello'
str(11.5)
'11.5'
str([1, 2, 3])
'[1, 2, 3]'
Practicing Coding Interview Questions in Python

str() constructor

class NewClass:

def __init__(self, num): self.num = num
nc = NewClass(2)
print(nc.num)
2
str(nc)
'<__main__.NewClass instance at 0x105cdabd8>'
Practicing Coding Interview Questions in Python

str() constructor

class NewClass:

def __init__(self, num): self.num = num
def __str__(self): return str(self.num)
nc = NewClass(3)

str(nc)
'3'
Practicing Coding Interview Questions in Python

Accessing characters in a string

s = "interview"
s[1]
'n'
s[-2]
'e'
s[1:4]
'nte'
s[2:]
'terview'
s[:3]
'int'
Practicing Coding Interview Questions in Python

The .index() method

s = "interview"
s.index('n')
1
s.index('i')
0
Practicing Coding Interview Questions in Python

Strings are immutable

s[0] = 'a'
TypeError

 

.capitalize()
.lower()
.upper()
.replace()

Methods return a new string object

Practicing Coding Interview Questions in Python

Modifying methods 1

# 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
Practicing Coding Interview Questions in Python

Modifying methods 2

# 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
Practicing Coding Interview Questions in Python

Relation to lists

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']
Practicing Coding Interview Questions in Python

String methods with DataFrames

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
Practicing Coding Interview Questions in Python

String methods with DataFrames

D['name'] = # we will modify this column
Practicing Coding Interview Questions in Python

String methods with DataFrames

D['name'] = D['name']
Practicing Coding Interview Questions in Python

String methods with DataFrames

D['name'] = D['name'].str
Practicing Coding Interview Questions in Python

String methods with DataFrames

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

Let's practice!

Practicing Coding Interview Questions in Python

Preparing Video For Download...