Python : String Manipulations
Tags: python, tutorial, beginners
Published: 2022-04-23 14:48:26

---
title: Python : String Manipulations
published: true
description: 
tags: Python, tutorial, beginner
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wefyji6jrkfta5ro8z7u.jpg
series: Python crash course
---

The Python crash course is free and will be posted here on dev.to. I will publish a new article every two days or so. To not miss anything, you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @EricTheCoder_

# String Manipulations

Let's now see in a little more detail how to create and manipulate character strings (Strings) with Python.

A variable of type String can be created with single or double quotes

```python
name = 'Mike'

# or

name = "Mike"

```

Python allows you to insert special characters into your Strings.

```python
message = "Hello \nWorld"
print(message)
# Hello
# World
```

The special character “\n” will be replaced by a line break. Python provides you with several special characters. Here is a list: [https://www.w3schools.com/python/gloss_python_escape_characters.asp](https://www.w3schools.com/python/gloss_python_escape_characters.asp)

### Interpolation

Using the “f” prefix displays the contents of the variable specified between the brackets {}

```python
name = "Mike"

print(f"Hello {name}")
# Hello Mike
```

Python can also execute any expression inside the {} brackets, so this concept can become very powerful. Here is an example:

```python
name = "Mike"

print(f"Hello {name.upper()}")
# Hello MIKE
```

It is also possible to join two Strings with the "+" (plus) operator

```python
name = "Mike"

print("Hello " + name)
# Hello Mike
```

### Ignore special characters

Using the “r” prefix displays the contents of the String as is. That is to say without taking into account special characters (ex. \n)

```python
message = r"https:\\example.com\index.html"
print(message)
# https:\\example.com\index.html
```

Here the use of the “r” prefix allows the path to be displayed correctly. Otherwise Python would have interpreted the double backslash "\\\" as a special character.

### String over multiple lines

Python also allows you to create a String exactly as entered even with line breaks. To do this you must use three quotes.

```python
message = """This is multiline
String that is easier to
read and assign"""

print(message)
# This is multiline
# String that is easier to
# read and assign
```

As a result, reading the String in the code is very explicit.

### Retrieving part of String

Python allows to retrieve only part of the String.

A String variable is indeed composed of several characters that can be read one by one or in groups. Here is some example

```python
product = "iPhone 12"
# position 012345678

print(product[0]) 
# i

print(product[2]) 
# h

print(product[1:6])
# Phone
```

Each character is associated with a position number. The first position is always 0. To access a particular position, it must be specified between square brackets []

Note that it is not possible to modify the String in this way. Any attempt to modify will return an error.

```python
product = "iPhone 12"
product[0] = "e"

# TypeError: 'str' object does not support item assignment
```

It is possible to access the characters of the String from the end.

```python
message = "Hello World";

print(message[-1])
# d
```

Position -1 represents the last character, -2 the penultimate, and so on.

When retrieving several characters, if one of the two positions is omitted, the retrieval will be from the beginning of the String

```python
message = "Hello World";

print(message[:5])
# Hello

print(message[-5:])
# World
```

### String Manipulations

Python has several functions that allow you to transform the contents of the String. Here are a few :

Uppercase and lowercase conversion

```python
name = 'Mike Taylor'

print(name.lower())
# mike taylor

print(name.upper())
# MIKE TAYLOR

```

Remove white spaces before and after a String

```python
message = "  Hello World        "

print(message.strip())
# "Hello World"

```

Return the number of characters in the String

```python
name = "Mike Taylor"

nb_char = len(name)

print(nb_char)
# 11
```

Change the first letter of a String to uppercase

```python
name = "mike"

name_cap = name.capitalize() 

print(name_cap)
# Mike
```

Change the first letter of all words in a String to uppercase

```python
name = 'mike Taylor'

name_title = name.title() 

print(name_title)
# Mike Taylor
```

Check if the String starts or ends with a particular character or characters

```python
name = 'Mike'

print(name.startswith('M')) 
# True

print(name.endswith('ke')) 
# True
```

Replace part of the String with other characters

```python
name = "Mike"

new_name = name.replace('M', 'P')

print(new_name)
# Pike
```

Return the position of a specific character

```python
name = "Mike"

print(name.find('k'))
# 2
```

Note that the first position always starts at zero and if the character is not found, the function will return -1



## Conclusion
That's all for today, I'll post a new article every other day or so. To make sure you don't miss anything, you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @ EricTheCoder_</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>