= "Python programming"
course
type(course)
#> <class 'str'>
len(course)
#> 18
3 String
Python
R
<- "R programming"
course_r
typeof(course_r)
#> [1] "character"
length(course_r)
#> [1] 1
nchar(course_r)
#> [1] 13
3.0.1 Slicing
Python
0]
course[#> 'P'
-1]
course[#> 'g'
0:3]
course[#> 'Pyt'
3]
course[:#> 'Pyt'
0:]
course[#> '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
= "Kittipos"
first = "Sirivongrungson"
last # Simple
+ " " + last
first #> 'Kittipos Sirivongrungson'
# Advance
print(f"{first} {last} is {len(first + last)} letter long")
#> Kittipos Sirivongrungson is 23 letter long
R
<- "Kittipos"
first <- "Sirivongrungson"
last # Simple
paste(first, last)
#> [1] "Kittipos Sirivongrungson"
# Advance
::glue("{first} {last} is {nchar(paste0(first, last))} letter long")
glue#> Kittipos Sirivongrungson is 23 letter long
3.0.4 String Methods
Python
Copy on modify
= " Python programming "
course
# Copy on modify
course.upper() #> ' PYTHON PROGRAMMING '
# Original is intact
course #> ' Python programming '
Basic formatting
course.upper()#> ' PYTHON PROGRAMMING '
course.lower()#> ' python programming '
course.title()#> ' Python Programming '
Strip white spaces
course.strip()#> 'Python programming'
# left
course.lstrip() #> 'Python programming '
# right
course.rstrip() #> ' Python programming'
Find and replace character
= " Python programming "
course
"pro")
course.find(#> 8
"p", "j")
course.replace(#> ' Python jrogramming '
Logical testing with string
"pro" in course
#> True
"java" not in course
#> True
3.0.5 Format String
Group 3 digits with ,
= 1000000
x f"{x:,}"
#> '1,000,000'
round digits
= 2/3
x f"{x:.2f}"
#> '0.67'
3.0.6 String Unpacking Trick
= 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
line *fields, homedir, sh = line.split(':') uname,
':')
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):
*tail = items
head, return head + sum(tail) if tail else head
sum([1, 2, 3])
#> 6