%%
date:: [[2023-04-02]]
%%
# [[String manipulation in Python]]
## Removing leading or trailing characters
`string = string.lstrip(' "\n')`
`string = string.rstrip(' "\n')`
This removes ` `, `"`, and `\n` from the left or the right of the string. It stops matching when a character is encountered from either direction that does not match the criterion.
## Determine whether a string starts or ends with a substring
```python
if string.startswith('text at start'):
print(string)
```
```python
if string.endswith('text at start'):
print(string)
```
You can optionally specify a start and end for a part of the string you want to search.
```python
string = 'This is a string. Hello!'
print(string.endswith('is', 1, 4))
print(string.endswith('is', 1, 10))
```
The above will yield the output:
```python
True
False
```
This is because the first ten characters of the string did not end in `is`.
## Count length of string
`len(string)`, 1-based
You can use this to count the leading spaces in a string:
```python
oldString = ' Hola'
newString = oldString.lstrip(' ')
print('number of spaces = ', len(oldString)-len(newString))
```
## Remove first or last X characters from string
```python
string = 'hippopotamus'
print(string[5:])
print(string[:5])
```
```python
potamus
hippopo
```
## Replace characters or substring in string
```python
string.replace(substring, newString, numOccurrences)
```
where `numOccurrences` is an optional integer. If it is not specified, all instances of `substring` will be replaced by `newString`.
## Split a string into an array based on a character
`split()`
By default, this function divides a string by the spaces in it (i.e., it breaks a string into words, with each word being a member of an array)
## String splicing
You can remove the last X characters of a string by using this:
```python
string = 'My string here'
string = string[:-5]
print(string) # My string
```
The `:` represents which part of the string you want to save. To remove all but the first five characters, use:
```python
string = 'My string here'
string = string[5:]
print(string) # My st
```
## Capitalize every word
You can use `.title()` to change a string such that every word of it is capitalized.
```python
string = "change THIS weirD STRING"
newString = string.title()
```
Note that this counts text after an apostrophe as a word, so unfortunately, `Bigby's hand` would be converted to `Bigby'S Hand`. To avoid this, you can add `replace()`:
```python
string = "change THIS weirD STRING"
newString = string.title().replace("'S","'s'")
```