String Operations Flashcards

1
Q

Filter on a single string value

strings

2 alternatives

A
df_filtered = data[data.col1 == "A"]
df_filtered = data.query("col1 == 'A'")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Filter on multiple string values

strings

3 alternatives

A
df_filtered = data[(data.col1 == "A") | (data.col1 == "B")]
df_filtered = data[data.col1.isin(["A", "B"])]
df_filtered = data.query("col1 == 'A' | col1 == 'B'")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Filter on the length of a string

strings

A
df_filtered = data[data.col1.str.len() > 4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Filter on a substring

string

3 alternatives

A
df_filtered = data[data.col1.str.startswith("Jo")]
df_filtered = data[data.col1.str.endswith("n")]
df_filtered = data[data.col1.str.contains("ak")]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Make the string filtering case-insensitive

strings

A
df_filtered = data[data.col1.str.contains("ak", case = False)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Make the string filtering ignore missing values

strings

A
df_filtered = data[data.col1.str.startswith("Jo", na = False)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Filter on the type of character in the string

strings

A
df_filtered = data[data.col1.str.isalnum()]

Other keywords:
- all characters are upper-case : isupper()
- all characters are lower-case : islower()
- all characters are alphabetic : isalpha()
- all characters are numeric : isnumeric()
- all characters are digits : isdigit()
- all characters are decimal : isdecimal()
- all characters are whitespace : isspace()
- all characters are titlecase : istitle()
- all characters are alphanumeric : isalnum()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Change case of a string

A
myname = "Michael Lemay"
str.upper(myname)
str.title(myname)
str.lower(myname)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

String formatting

A

Traditional formatting

name = “John”
age = 30

message = “My name is {} and I’m {} years old.”.format(name, age)

message = f”My name is {name} and I’m {age} years old.”python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Split string

A

text = “This is a sample text.”
words = text.split()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly