3  String

Python

course = "Python programming"

type(course)
#> <class 'str'>
len(course)
#> 18

R

course_r <- "R programming"

typeof(course_r)
#> [1] "character"
length(course_r)
#> [1] 1
nchar(course_r)
#> [1] 13

3.0.1 Slicing

Python

course[0]
#> 'P'
course[-1]
#> 'g'
course[0:3]
#> 'Pyt'
course[:3]
#> 'Pyt'
course[0:]
#> 'Python programming'
course[:]
#> 'Python programming'

R

substr(course_r, 1, 1)
#> [1] "R"
substr(course_r, 1, 4)
#> [1] "R pr"

3.0.2 Escape

Python

print("python \"programming\" \nis 'fun'")
#> python "programming" 
#> is 'fun'

R

cat("R\nis \"also\" 'fun'")
#> R
#> is "also" 'fun'

3.0.3 Join String

Python

first = "Kittipos"
last = "Sirivongrungson"
# Simple
first + " " + last
#> 'Kittipos Sirivongrungson'
# Advance
print(f"{first} {last} is {len(first + last)} letter long")
#> Kittipos Sirivongrungson is 23 letter long

R

first <-  "Kittipos"
last <-  "Sirivongrungson"
# Simple
paste(first, last)
#> [1] "Kittipos Sirivongrungson"
# Advance
glue::glue("{first} {last} is {nchar(paste0(first, last))} letter long")
#> Kittipos Sirivongrungson is 23 letter long

3.0.4 String Methods

Python

Copy on modify

course = " Python programming "

course.upper() # Copy on modify
#> ' PYTHON PROGRAMMING '
course # Original is intact
#> ' Python programming '

Basic formatting

course.upper()
#> ' PYTHON PROGRAMMING '
course.lower()
#> ' python programming '
course.title()
#> ' Python Programming '

Strip white spaces

course.strip()
#> 'Python programming'
course.lstrip() # left
#> 'Python programming '
course.rstrip() # right
#> ' Python programming'

Find and replace character

course = " Python programming "

course.find("pro")
#> 8
course.replace("p", "j")
#> ' Python jrogramming '

Logical testing with string

"pro" in course
#> True
"java" not in course
#> True

3.0.5 Format String

Literal string interpolation

Group 3 digits with ,

x = 1000000
f"{x:,}"
#> '1,000,000'

round digits

x = 2/3
f"{x:.2f}"
#> '0.67'

3.0.6 String Unpacking Trick

line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')
line.split(':')
#> ['nobody', '*', '-2', '-2', 'Unprivileged User', '/var/empty', '/usr/bin/false']
uname
#> 'nobody'
fields
#> ['*', '-2', '-2', 'Unprivileged User']
homedir
#> '/var/empty'

3.0.7 Cool thing

def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head
sum([1, 2, 3])
#> 6