Python basics
  • Tutorial
  • Exercices
  • About
  1. Fundamentals
  2. 4-Strings
  • Introduction
    • Python
  • Fundamentals
    • 0-Basic Syntax
    • 1-Variables
    • 2-Data types
    • 3-Numbers
    • 4-Strings
    • 5-Lists
    • 6-Booleans
    • 7-Loops
    • 8-Functions
    • 9-Dictionary
  • Advanced
    • 10-Numpy
    • 11-Matplotlib
    • 12-DataFrame
  • CLI
    • Exercices
    • Solutions
  • Git
    • Git introduction
    • Git branch
    • Git exercices
  • SQL
    • SQL Exercices
    • SQL Solutions

On this page

  • Strings as arrays
    • Length
    • Check string
  • Slice strings
  • Modify strings
    • Lower - upper
    • Whitespace
    • Replace
    • Split
  1. Fundamentals
  2. 4-Strings

4-Strings

Notebook

Link to the Google Colaboratory notebook: 4-Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

Strings as arrays

Strings in Python are arrays of bytes representing unicode characters.

A single character is simply a string with a length of 1.

You can access elements of a string using square brackets:

name = "Evry"
print(name[0], name[2])
E r
Note

Since strings are arrays, we can loop through it like arrays.

name = "Evry"
for letter in name: 
    print(letter)
E
v
r
y

Length

You can get the length of a string using the len function.

name = "This is a test sentence"
print(len(name))
23

Check string

You can check if a string is inside another one.

To do so, you can use the in syntax:

sentence = "This is a test sentence"
word = "sentence"
print(word in sentence)
True

Slice strings

In Python, we can return a range of characters using the slice syntax.

Specify the start and the end index, separated by a colon:

name = "This is a sentence"
print(name[3:15])
s is a sente
Note

To access from the start or the end, use : :

name = "This is a sentence"
print(name[:5]) # from the start
print(name[5:]) # to the end
This 
is a sentence

Modify strings

Python has built-in methods to modify strings.

Lower - upper

You can convert to uppercase or lowercase a string with the functions .upper() or .lower():

name = "eVry"
print("Lower", name.lower())
print("Upper", name.upper())
Lower evry
Upper EVRY

Whitespace

You can remove whitespace from a string that is located at the beginning or the end.

Use the .strip() function:

sentence = "       This is a sentence !     "
print(sentence.strip())
This is a sentence !

Replace

Sometimes it can be usefull to replace a string by another value.

The .replace function does it:

sentence = "This are a sentence !"
print(sentence.replace("are", "is"))
This is a sentence !

Split

The split() method returns a list where the text between the specified separator becomes the list items.

sentence = "This is a sentence !"
print(sentence.split())
['This', 'is', 'a', 'sentence', '!']
3-Numbers
5-Lists
 

Copyright 2023, Clément Bernard