Set Up

library(reticulate) # to use python in RStudio
library(tidyverse) # data wrangling and plotting with R

R code chunks are in light pink, while python in light blue.

Types of strings


It is interesting to know that there are two special types of strings in Python:

  • raw string: A raw string is not processed by the Python interpreter; the content of the string is kept as it is (example).
  • f-strings: An f-string, also called formatted string literal, can dynamically create a new string by using the values of variables ([example][Formatted String Literals])

Raw Strings

print('R is fun. \nSo is Python') # normal string, \n will be executed which creates a new line
## R is fun. 
## So is Python
print(r'R is fun. \nSo is Python') # raw string, \n will be kept as it is
## R is fun. \nSo is Python

Formatted Strings Literals

With f-strings, we can define the format in many ways. For example

  • a is displayed as a string, and occupies a space of 8 characters
  • b is displayed as a floating type, and has 3 decimal places
  • c is a floating type displayed in a width of 9 characters, including 4 decimal places.
a = 'Thomas' ; b = 12.5 ; c = 4 / 3

print(f'a = {a:8s}, b = {b:.3f}, and c = {c:9.4f}')
## a = Thomas  , b = 12.500, and c =    1.3333

Simple demo of f-string in a function

def divide(dividend, divisor):
    '''
    print out the quotient and remainder of the division
    '''
    q = dividend // divisor
    r = dividend % divisor
    print(f'quotient is {q}, remainder is {r}.')

divide(9,4)
## quotient is 2, remainder is 1.