---
# System prepended metadata

title: 'Lesson 5: String Manipulation'
tags: [Python Workshop 沈煒翔]

---

---
tags: Python Workshop 沈煒翔
---

# Lesson 5: String Manipulation

## String

In most programming languages, a character is a single letter and a string is a sequence of characters. However, there is only string in Python.

```python
# All these are considered "str" data type in Python
s1 = "a"
s2 = 'abcdefg' # ' and " are the same
s3 = 'I like to eat apple.'
s4 = '今天天氣不錯'
```

Strings in Python are arrays of single characters.

```python
s = 'Hello World'

# We can index the characters using its integer position
print(s[0])
# >>> H

# We can loop through a string using for loop
for c in 'Hello':
    print(c)
# >>> H
# >>> e
# >>> l
# >>> l
# >>> o
```

It shares many properties with list.

```python
s = 'Hello'
l = [1, 2, 3]

# len() to check the length of the string
print(len(s)) # >>> 5
print(len(l)) # >>> 3

# "in" to check if a substring exists
'ello' in s # >>> True
'e' in s # >>> True
5 in l # >>> False

# slicing to slice the string
print(s[1:3]) # >>> 'el'
print(l[1:3]) # >>> [2, 3]
```

In Python, strings are immutable (like tuple), which means it cannot be changed.

## String operators

'+' is for concatenate

```python
s1 = 'Hi!'
s2 = 'Hello!'

s3 = s1 + s2 # >>> 'Hi!Hello!'
```

'*' is for repetition

```python
s1 = 'Hey!'

s2 = s1 * 3 # >>> 'Hey!Hey!Hey!'
```

'==' and '!=' for comparison

```python
'Apple' == 'Apple' # >>> True
'Apple' == 'apple' # >>> False
```

### Exercise
Change every 'e' to 'a' in the given string.

```python
s = 'I like to eat apples.'
```

```python
s = 'I like to eat apples.'
s2 = ''

for ch in s:
    if ch != 'e':
        # s2 = s2 + ch
        s2 += ch
    else:
        s2 += 'a'

print(s2)
```

Decode the following encryption.

```python
inputs = '3a1b5c'

# Hint: you can cast string to int like this: int('5') -> 5

print('aaabccccc')
```

```python
inputs = '3a1b5c'
s2 = ''

for i, ch in enumerate(inputs):
    if i % 2 == 0:
        s2 += inputs[i+1] * int(ch)
    
print(s2)    
```

```python
inputs = '3a1b5c'
s2 = ''

for i, ch in enumerate(inputs):
    if i % 2 == 0:
        num = int(ch)
	else:
        s2 += inputs[i+1] * num
    
print(s2)    
```

```python
inputs = '3a1b5c'
s2 = ''

for i, ch in enumerate(inputs):
    if ch in ['1','2','3','4','5','6','7','8','9','0']:
        num = int(ch)
    else:
        s2 += ch * num
    
print(s2)      
```

## Useful string functions

In dictionaries, we can use .keys() to get all the keys, .values() to get all the values. There are the built-in functions of the dictionary data type.

In string, there are also **a lot of** built-in functions that you can use. You don't need to remember all of them.

Upper case and lower case

```python
s = 'Hello World!'

print(s.upper()) # >>> 'HELLO WORLD!'

print(s.lower()) # >>> 'hello world!'
```

Replace string
```python
s1 = 'I like apples.'
s2 = s1.replace('apples', 'grapes') # replace the first substring with the second substring

print(s2) # >>> 'I like grapes.'
```

Split string
```python
s1 = "Hello, World!"
s2 = s1.split(",") # split the string into a list of strings with the separator

print(s2) # >>> ['Hello', ' World!']

# If no separator is specified, white space is used.
s1 = "Hello, World!"
s2 = s1.split()

print(s2) # >>> ['Hello,', 'World!']
```

### Exercise
Split the strings into words.

```python
s = 'Last Friday, I skipped the class.'

# >>>　['Last', 'Friday', 'I', 'skipped', 'the', 'class']
```

## String formatting

We can format the string to include some variables inside the string. We put a 'f' before the string to let Python know we are formmating this string and use the {} syntax for formatting.

```python
age = 15
name = 'Jack'

s = f'{name} is {age}.'
```

There is some other ways to format the Python string, but not recommended. However, some people still use it so we better know what they're doing.

```python
age = 15
name = 'Jack'

s = '%s is %d.' % (name, age) # you have to remember the code
s = '{} is {}.'.format(name, age) # bad readability
```

Also, we can use string formatting when dealing with float numbers. The syntax is 

```python
f'{value:{width}.{precision}}'
```

value: the number you want to print
width: the number of characters used for display (may exceed)
precision: the number of characters used after the decimal point

```python
pi = 3.14159265

print(f'{pi}') # >>> '3.14159265'
print(f'{pi:.2f}') # >>> '3.14'
print(f'{pi:5.2f}') # >>> ' 3.14'
print(f'{pi:05.2f}') # >>> '03.14'
# the f here is for floating numbers, use 'd' for integer
```

### Exercise
Print the given list in a beautiful right-aligned way

```python
l = [1.35, 2, 3.3578, -3.56, 1/7]
```
![](https://i.imgur.com/o5kaurv.png)

## Practice

https://leetcode.com/problems/two-sum/
https://leetcode.com/problems/single-number/