Strings Flashcards
string slices:
Slices (substrings) in python can take a third argument, which is the step size (or “stride”) that is taken between indices. It is similar to the third argument for the range() function. The format for slices then becomes [::]. By default the step size is 1.
Reversing a string using [::-1] is conceptually similar to traversing the string from the last character to the beginning of the string using backward steps of size 1.
fruit = "banana" print( fruit[::2] ) print( fruit[1::2] ) print( fruit[::-1] ) print( fruit[::-2] )
output:
bnn
aaa
ananab
aaa
strings are immutable
A core property of strings is that they are immutable. This means that they cannot be changed. For instance, you cannot change a character of a string by assigning a new value to it.
string methods:
a.strip( )
a.split(“!~,.\n “)
s = “-“.join(a)
a. upper( )
a. lower( )
a. find( )
a. replace( )
a.strip( )
strip() removes from a string leading and trailing spaces, including leading and trailing newlines and other characters that may be viewed as spaces. There are no parameters. See the following example (the string is bordered by [ and ] to show the effect):
a.split(“!~,.\n “)
split() splits a string up in words, based on a given character or substring which is used as separator. The separator is given as the parameter, and if no separator is given, the white space is used
s = “-“.join(a)
join() is the opposite of split(). join() joins a list of words together, separated by a specific separator. This sounds like it would be a method of lists, but for historic reasons it is defined as a string method.
a.upper( )
a.lower( )
upper() creates a version of a string of which all letters are capitals. lower() is equivalent, but uses only lower case letters. Neither method uses parameters.
a.find( )
find() can be used to search in a string for the starting index of a particular substring. As parameters it gets the substring, and optionally a starting index to search from, and an ending index. It returns the lowest index where the substring starts, or -1 if the substring is not found.
a.replace( )
replace() replaces all occurrences of a substring with another substring. As parameters it gets the substring to look for, and the substring to replace it with. Optionally, it gets a parameter that indicates the maximum number of replacements to be made.
strings are immutable, so the replace() function is not actually changing the string. It returns a new string that is a copy of the string with the replacements made.
ASCII
ord( “A“)
chr(65)
print( ord( 'A' ) ) print( ord( 'a' ) ) print( chr( 65 ) ) print( chr( 97 ) ) print( "orange" < "ordinal" )
output: 65 97 A a True
UTF-8
alpha = “\u0391”
for i in range( 25 ):
print( chr( ord( alpha )+i ), end=” “ )
Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω