Lesson 4: .strip()

.strip() method is a convenient string method to clean whitespaces or other characters from the beginning and end of a string. It can be very handy when working with raw data, files, email data, multiples lines etc.

Function 1: .strip()

.strip() method removes leading and trailing whitespaces from a string. Either:

  • According to the character passed inside parenthesis as parameter or,
  • It will remove whitespaces if no argument is passed inside the parenthesis

Used Where?

  • Cleaning data
  •  Removing specific leading and trailing characters from a string

Syntax do(s)

1) Type the characters you’d like to be wiped inside the parenthesis.

2) If no parameter is given .strip() removes whitespaces.

Syntax don't(s)

1) Don’t forget to pass your parameter inside parenthesis inside quotes.

Example 1

>>> name = ”    asdas          “
>>> a = name.strip()
>>> print(a
)

“asdas”

Notice how ending is exclusive, index starts from 0 and step is 1 since it’s not specified.

Example 2

Remember range() function? and then list() function.

>>> lst = list(range(10))
>>> print(lst)
>>> print(lst[2:6])

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5]

Example 3

Let’s use a step as well

>>> lst = list(range(10))
>>> print(lst)
>>> print(lst[2:6:2])

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4]

Tips

1- You don’t have to type the characters you want to removed in a specific order. You can just throw them all together and .strip() method will remove all of them on both sides.

Let’s see some examples.

Example 5

Below example will give everything until last 2 elements

>>> a = list(range(10))
>>> print(a[:-2])

[0, 1, 2, 3, 4, 5, 6, 7]

Example 6

And everything until last 2 elements with steps of 2

>>> a = list(range(10))
>>> print(a[:-2:2])

[0, 2, 4, 6]

Advanced Concepts (Optional)

1- rstrip

2- lstrip

Let’s see an example.

Example 6

And everything until last 2 elements with steps of 2

>>> a = list(range(10))
>>> print(a[:-2:2])

[0, 2, 4, 6]

Example 6

And everything until last 2 elements with steps of 2

>>> a = list(range(10))
>>> print(a[:-2:2])

[0, 2, 4, 6]

Exercise 4

Lesson 5

dir()

Clarence Alphonse Gagnon - ferme de st antoine


Clarence Alphonse Gagnon

Ferme de St Antoine

Ferme de St Antoine by Clarence Alphonse Gagnon