• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/57

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

57 Cards in this Set

  • Front
  • Back

3 types of strings in Python

str: unicode and ASCII


bytes: for binary data, including encoded text


bytearray: mutable variant of bytes

Does python have a type for characters?

No. they're just a one-character string

create an empty string

S = ''

Do escape sequences work in Python?

yes

repeat a string 2x

str * 2

create a raw string

ignores escape sequences




S = r'\temp\spam\'

create a byte string

B = b'sp\xcm\'

create a unicode string

U = u'sp\u004c'

index a string

S[i]

slice a string

S[:]

get the length of a string

len(str)

search a string

myS.find('str')

remove whitespace from a string

myS.rstrip()

replace characters in a string

myS.replace('pa', 'xx')

split a string on a delimiter

myS.split(',')

check if a string contains only digits

myS.isdigit()

convert a string to lowercase

myS.lower()

check if a string ends with a specified set of characters

myS.endswith('spam')

delimiter join

'Spam'.join(strlist)




#strlist is the list created when you split on delimiters

print each character in str

for x in str: print(x)

check if 'spam' is in a string

'spam' in str

Why are ' and " interchangeable in Python?

so you can embed one of them inside the other without needing an escape sequence




'she said, "yes"'

What does Python automatically do to adjacent string literals? How do you prevent his?




'knight' 'knight'

concatenates into a single string




use a comma to separate




'knight', 'knight'

In Python, is there a null character at the end of a string?

no





Can Python also use / for directory addresses?

yes because it tries to interpret them portably, so you're not just restricted to \

create a multiline block string

"""


line 1


line 2


"""




#embeds newline characters so it will look like what you typed when it's printed

Normally any comments added to the right of a multiline string are included in it. How can you force python to ignore the comments to the right of a multiline string? What's the downside?

instead of """, use ( ) around the whole thing




downside: need to use ' ' around each individual part and newline is not included automatically




menu = (


'spam', #comment


'\neggs' # comment)



When are triple-quoted strings also used as documentation strings/multiline comments?

when they appear at specific points in the file (TBD)

Is this a valid expression in Python?

'str'+9

no, Python doesn't automatically convert numbers to strings when concatenating

difference between .find() and in

in returns boolean




find() returns int position of substring

slicing: get the second-to-last character in a string

S[-2]

get all characters after the first letter from a string

S[1:]

get charaters 1-3 of 'spam'

'spam'[1:4]

slicing: if omitted, what does the left bound default to? right bound?

left bound defaults to 0


right bound defaults to length

copy 'spam'

s = 'spam'[:]

optional third index when slicing

stride or step: can use to skip items or reverse order

What does this code do?




'ahfdsarea'[1:5:2]

from characters 1 up to 5, it gets every 2nd letter

collect 'hello' in opposite order

S = 'hello'[::-1]

Compare this code:




'spam'[1:3]


'spam'[slice(1,3)]

equivalent

convert "42" to a number


convert 42 to a string

int("42")


str(42)

change this code so it's valid:




'42' + 1

'42' + str(1)

difference between str(42) and repr(42)

both create a string, but with repr(42) you can recreate the original object, which you can't do with str(42)

convert to a floating-point number: '1.234'

float('1.234')

convert a single character to its ADCII code value, then perform the inverse operation

ord('s')


chr(115)

In Python, _____ and ____________ generally work across many types, but _______________ are type-specific

expressions and built-in functions work across many types, but methods are type-specific

How do you get a list of all the names of methods for strings? List with names AND descriptions of all methods?

dir(str): names only


help(str): names AND descriptions of methods




help(str.capitalize): look up this method only

How can you make in-place changes to a string?

use a bytearray: it's mutable




most of the time it's simpler to just use str and replace() though, which creates a new string object

If you have a very large string object that needs multiple changes, what can you do?

probably too large for a bytearray, so convert to a list with list(s) and then perform operations on list components since it's mutable. Once you're done, use S = ''.join(myList) to join the characters back into a string




#in this case, there's no delimiter so the delimiter at the beginning is empty

chop up a string based on delimiters

line = 'aaa bbb cccc'


list = line.split()




#since split is empty, it will split on whitespace. otherwise. it will split based on the character or string you pass to it

Today, should you use string methods or the string module?

string methods only. the string module is ONLY maintained for backwards compatibility and should not be used in new code

string formatting expression vs string formatting method call

expression: '...%s....' % (values)


'that is %d dead %s' % (1, 'bird')




method call (newer): '...{}...'.format(values)

dictionary-based formatting expression example: template with substitution targets

'%(qty)d more %(food)s' % {'qty' : 1, 'food' : 'spam'}




# 1 more spam

Formatting method: How is it choosing what to format?




template = '{0}, {1}, and {2}'


template.format('spam', 'ham', 'eggs')

formatting by position




spam, ham, and eggs





Formatting method: How is it choosing what to format?




template = '{motto}, {pork}, and {food}'


template.format(motto='spam', pork='ham', food='eggs')

formatting by keyword




spam, ham, and eggs

Formatting method: How is it choosing what to format?




template = '{motto}, {0}, and {food}'


template.format('ham', motto='spam', food='eggs')

formatting by keyword AND position




spam, ham, and eggs

Formatting method: How is it choosing what to format?




template = '{}, {}, and {}'


template.format('spam', 'ham', 'eggs')

by relative position




spam, ham, and eggs

Which should you use, formatting expression or format method?

both are still used and are very similar