String Operations Flashcards
Pull out the first digit in a string
stringname[0]
Pull out the nth digit of a string
stringname[n]
Pull out the last digit of a string (using negative indexing)
stringname[-1]
find the length of a string
len(stringname)
slice the first three digits of a string
stringname[0:3]
get every second letter of a string
stringname[::2]
get every second letter of a string starting from the 4th letter to the 8th
stringname[3:8:2]
What is
‘1’ + ‘2’
‘12’
how would i replicate a string three times
3 * “string goes in here”
OR
3 * stringname
how do i make a new line in a printed string
\n
how to i add a tab in a printed string
\t
how do i put a backslash in a printed string
put two \
OR
print(r”string goes \ in here”)
where do you put an r for raw string
just before the first “ of the string
what is the general format for operations?
variable.operation()
convert stringname to uppercase letters
newstringname = stringname.upper()
convert stringname to lowercase letters
newstringname = stringname.lower()
turn all instances of “michael” into “janet” in stringname - NOT RegEx
stringname.replace(“Michael”, “Janet”)
how do you link repeated commands
stringname.function().function().function()
write a command to figure out at what index number “Jack” starts in the string “Michael Jackson”
name = “Michael Jackson”
name.find(‘Jack’)
what is output in a find command if the substring cannot be located in the string
-1
what is the import to import Regular Expressions
import re
how do you check whether there is a match for something in regular expression
result = re.search(pattern, stringname)
returns as NoneType or re.Match
what would you use to match any digit in RegEx
\d
what would match any non-word character in RegEx
\W
what would match any white space character in RegEx
\s
in RegEx, what is used to locate all of the occurrences of a specified pattern in a string
matches=re.findall(pattern, stringname)
outputs each individual instance in a list
in RegEx, how would you separate a string into a list each time there was a space
list = re.split(“\s”, stringname)
In RegEx, how would you replace all instances of “Tom” with “Mary”
output = re.sub(“Tom”, “Mary”, stringname)
stringname.replace(“Matthew”, “Mary) is similar to what command in RegEx
re.sub(“Matthew”, “Mary”, stringname)
how is search in RegEx different from find
find returns the index value for that substring (ie returns 9 for “jack” in “michael jackson”)
search tells you whether or not there is a match for such thing, and then you can use match.group() to display the match