1b. String Flashcards
String indexing and slicing
Str [ start : stop : Step]
stop = “up to but not including”
stop can be longer than the len of itself
String reverse
Str [ : : -1]
String new line
\n
String “tab”
\t
how to break up a sentence into list of words
str. split() -> all instance
str. partition() -> first instance
F string with dictionary
Single quote outside then double quote inside
print(f’The variable is {dict[“key”]}’)
“in” String
name = “Zophie”
‘Zo’ in name => True
zo => False
multiline string
can quote it using ‘’’ ‘’’
str = ‘'’sdkfjskdfj
sdkfjskdfj
jsdkfjds’’’
raw string
r’This is Shelly's cat’
useful for a lot of backslash e.g. regular expression
string method
4 main type of str charater
mystr = ‘hello world!’
mystr. islower() => true (neglect space, false if only space)
mystr. isupper()
mystr. upper()
mystr. lower()
4 main type: num, alpha, space, special isalpha isalnum => alpha + num isdecimal => no special, i.e. nataural number only ispace => can be multiple spaces
.startswith
.endswith
join / split / partition
string alignment, trim, replace
‘Hello’.ljust(10)
‘Hello’.rjust(10, ‘-‘)
‘Hello.center(10, ‘=’)
’ Hello ‘.strip() / rstrip() / lstrip
“SpamSpamBaconSpamEggsSpam”.strip(‘ampS’)
‘Hello’.replace(‘e’, ‘XYZ’)
string formatting (insert variable)
%s
fstring
string.format:
print(‘{0:=<8} | {1:-^8} | {2:.>8}’.format(11,22,33))
String formatting 3 method
name = ‘Mary’
age = 18
mystr = ‘Hello %s, you are age %s’ % (name, age) => old
mystr2 = ‘Hello {}, you are age {}’.format(name, age)
mystr5 = f’Hello {name}, you are age {age}’
Hello Mary, you are age 18
mystr3 = 'Hello {1}, you are age {0}'.format(name, age) mystr4 = 'Hello {b}, you are age {a}'.format(a=name, b=age)
Hello 18, you are age Mary
Number formatting with padding for int and floats
{a:=<8}
{ : “fill” alignment “total width” .length d/f}
alignment
a=11111
b=22
c=33
print(f’{a:=<8} | {b:-^8} | {c:.>8}’)
11111=== | —22— | ……33
***fill has to use with alignment
a=1.2355
print(f’{a:4.3}’) => 1.24
print(f’{a:4.3f}’) => 1.236
# integer numbers with minimum width print("{:5d}".format(12)) 12 # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) 1234 # padding for float numbers print("{:8.3f}".format(12.2346)) 12.235 # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) 00012 # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346)) 0012.235
https://www.programiz.com/python-programming/methods/string/format
control h in string
Str.replace(‘a’,’b’)
Change A to b