"You can put single quotes ' in a string with double quotes on the outside""You can put single quotes ' in a string with double quotes on the outside"
Strings : An immutable sequence of unicode characters
"You can put single quotes ' in a string with double quotes on the outside""You can put single quotes ' in a string with double quotes on the outside"
'and visa versa (")''and visa versa (")'
print(
"""muti-line strings
with three quotes""")muti-line strings
with three quotes
# 잘 알아둘것, 많이 사용
word='KAIST MFE Program'
# indexing
print(word[0],word[5],word[6],sep="/")
# slicing
# str[a:b:c] = start a, end b, jump c
# a is inclusive, b is exclusive, c can be minus
# default : a =0, b=n+1, c=1 but when c is minus then default : a=n, b=0(inclusive)
print(word[0:5],word[6:9],word[10:])
print(word[:2],word[-2:])
print(word[0:10:2])
print(word[::-1])K/ /M
KAIST MFE Program
KA am
KITME
margorP EFM TSIAK
text='Python strings are sliceable.'
text[10]'i'
length=len(text)
text[length]IndexError: string index out of range
text[length-1]'.'
a='Hello'; b='Python'
print(a+b, a*2+b*3, 'H' in a, 'm' not in a)HelloPython HelloHelloPythonPythonPython True True
'123'+1TypeError: can only concatenate str (not "int") to str
'123'+str(1)'1231'
int('123')+1124
# len, .find, .count, .lower, .upper, .split, .replace, .starswith, .endswith
# .isalpha, .isnumeric, .isalnum
# len is function, others are methods
print(
word,
len(word),
word.find('I'),
word.count(' '),
word.lower(),
word.upper(),
word.split(' '),
word.replace(' ','-'),
sep='\n'
)KAIST MFE Program
17
2
2
kaist mfe program
KAIST MFE PROGRAM
['KAIST', 'MFE', 'Program']
KAIST-MFE-Program
True
False
False
True
False
True
False
print(
word.startswith('K'),
word.endswith('M'),
word.isalpha(),
word.replace(' ','').isalpha(),
word.isnumeric(),
'123'.isnumeric(),
word.isalnum(),
word.replace(' ','1').isalnum(),
sep='\n'
)True
False
False
True
False
True
False
True
# string = immutable, not possible to modify
# method or operations on string != modify but make new string
sequence="ACGT"
sequence.replace("A","G")'GCGT'
sequence'ACGT'
id(sequence)2053186997616
sequence=sequence.replace("A","G")
did(sequence)2053183781744
# a mutable sequence of objects, important!!
# To create List object, use [] or list()
x1=[1,2,3,4]
x2=[1,1.0,1+0j,'one',None,True]
x3=[[1,2,3,4],[5,6,7],[8,9]] # nested list
# 리스트 안에는 무엇이든 올 수 있음
print(x1,x2,x3,sep='\n')[1, 2, 3, 4]
[1, 1.0, (1+0j), 'one', None, True]
[[1, 2, 3, 4], [5, 6, 7], [8, 9]]
e1=list()
type(e1)list
len(e1)NameError: name 'e1' is not defined
list('cat')['c', 'a', 't']
a_tuple=('abc')
list(a_tuple)['a', 'b', 'c']
# indexing -> original object, slicing -> make sub-list
myList=[5,2.3,'hello']
print(
myList[0],
myList[-1],
myList[-3]
)5 hello 5
many_types=[1,55.5,"Am I in a list?",True,"the end"]
print(
many_types[2:4],
many_types[2:],
many_types[:3],
many_types[-4:-2],
many_types[-2:-5:-1],
many_types[:-3],
many_types[:3:2],
many_types[:-2:2],
sep='\n'
)['Am I in a list?', True]
['Am I in a list?', True, 'the end']
[1, 55.5, 'Am I in a list?']
[55.5, 'Am I in a list?']
[True, 'Am I in a list?', 55.5]
[1, 55.5]
[1, 'Am I in a list?']
[1, 'Am I in a list?']
# Multidimensional lists can alse be indexed and sliced.
x=[[1,2,3],[4,5,6],[7,8,9,0]]
x[0][1, 2, 3]
x[0][1]2
x[0][0:2][1, 2]
# List object is an immutable!!
colorList=['red','blue','green','black','white']
print(id(colorList),colorList)2665431628288 ['red', 'blue', 'green', 'black', 'white']
colorList[2]='yellow'
print(id(colorList),colorList)2665431628288 ['red', 'blue', 'yellow', 'black', 'white']
colorList[2:4]=['gray','purple']
colorList['red', 'blue', 'gray', 'purple', 'white']
colorList[1:4]='r e d'
colorList['red', 'r', ' ', 'e', ' ', 'd', 'white']
colorList[1:]=['orange']
colorList['red', 'orange']
L1=[1,2,3]; L2=[4,5,6]; L3=[7,8,9,0]
print(
L1+L2+L3,
[L1],
[L1]+[L2]+[L3],
sep='\n')[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[[1, 2, 3]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 0]]
print(
L1*3,
3*L1,
[L1]*3,
[L1+L2]*3,
[1,2,3] in [L1]+[L2],
sep='\n'
)[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
True
# len, min, max, del x[slice]
# x.append(value), x.extend(list), x.remove(value), x.count(value),
# x.insert(index, value), x.index(value), x.sort(), x.reverse()
x=[0,1,2,3,4,5,6,7,8,9]
del x[0] # 많이 사용
x[1, 2, 3, 4, 5, 6, 7, 8, 9]
del x[:3]
x[4, 5, 6, 7, 8, 9]
del x[:]
x[]
x=[0,1,2,3,4,5,6,7,8,9]
len(x)10
# in place
x.reverse()
x[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# not in place
sorted(x)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# in place
x.sort()
x[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
pockets=[5,3,6,7]
pockets_copy=pockets
pockets_copy.append(1)
pockets_copy[5, 3, 6, 7, 1]
# pockets_copy is just labeling of pockets
pockets[5, 3, 6, 7, 1]
# [:] makes copy of original list object
# At list [:] is copy, but at Array(numpy) [:] is view
pockets_realcopy=pockets[:]
pockets_realcopy.append(1)
pockets_realcopy[5, 3, 6, 7, 1, 1]
pockets[5, 3, 6, 7, 1]
pockets_method=pockets.copy()
pockets_method.append(1)
pockets_method[5, 3, 6, 7, 1, 1]
pockets[5, 3, 6, 7, 1]
t=(12345,54321,'hello')
t(12345, 54321, 'hello')
# if it contains a single variables, should include comma!
x=(2)
type(x)int
x=(2,)
type(x)tuple
a=1,2,3,'hello'
a(1, 2, 3, 'hello')
w,x,y,z=a
print(w,x,y,z)1 2 3 hello
x,_,y,_=a
print(x,y)1 3
x,*y=a
print(x,y)1 [2, 3, 'hello']
# can be indexed or sliced.
x=(1,2,3,4,5,6,7,8,9)
print(
x[5],
x[-3],
x[3:7],
x[3:7:2],
sep='\n'
)6
7
(4, 5, 6, 7)
(4, 6)
# Tuples are immutable : impossible to add/remove/replace elements in a tuple
tup1=(12,34.56)
tup1[0]=100TypeError: 'tuple' object does not support item assignment
tup2=([1,2],[3,4])
tup2[0][0]=100
tup2([100, 2], [3, 4])
tup1=(1,2,3,4)
tup2='a','b','c'
tup1+tup2(1, 2, 3, 4, 'a', 'b', 'c')
tup1*3(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
'a' in tup2True
tup1[0:1]+tup2[1:](1, 'b', 'c')
tup1[0:1]+tup2[1]TypeError: can only concatenate tuple (not "str") to tuple
# concatenation
tup_even=tup1[1::2]+(6,)
tup_even(2, 4, 6)
# len, max, min, x.index, x.count
animals=('lama','sheep','lama',48)
len(animals)4
print(
animals.index('lama'),
animals.count('sheep'),
sep='\n')0
1
# to fix tuple, tuple -> list -> tuple
x_list=list(x)
x_list.reverse()
x=tuple(x_list)
x(9, 8, 7, 6, 5, 4, 3, 2, 1)
# tuple is faster than list!
%timeit x=[1,2,3,4,5]
%timeit x=(1,2,3,4,5)47.3 ns ± 0.743 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
10.2 ns ± 0.0818 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)
type({})dict
# two-value sequenced can convert to dict easy!
lot=[(1,2),(3,4),(5,6)]
dict(lot){1: 2, 3: 4, 5: 6}
los=['a1','b2','c3']
dict(los){'a': '1', 'b': '2', 'c': '3'}
dict(a=1,b=2,c=3){'a': 1, 'b': 2, 'c': 3}
a="abc"
dict(a=1,b=2,c=3){'a': 1, 'b': 2, 'c': 3}
dict1=dict(Name='Zara', Age=7, Class='First')
dict1{'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict1['Name']'Zara'
dict1['Age']=8
dict1['School']='ABC School'
dict1{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'ABC School'}
a='Town'
dict1[a]='Downtown'
dict1{'Name': 'Zara',
'Age': 8,
'Class': 'First',
'School': 'ABC School',
'Town': 'Downtown'}
# Check only key value!!
print(
'Name' in dict1,
'Age' in dict1,
'Country' in dict1,
'Country' not in dict1,
'Zara' in dict1,
sep='\n'
)True
True
False
True
False
# len, del x[key]
# x.clear(), x.items(), x.keys(), x.values(), x.update(dict2)
print(dict1, len(dict1), sep='\n'){'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'ABC School', 'Town': 'Downtown'}
5
del dict1['Town']
dict1{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'ABC School'}
dict1.clear()
dict1{}
del dict1
dict1NameError: name 'dict1' is not defined
dict1=dict(a=1,b=2,c=3)
dict1.keys()dict_keys(['a', 'b', 'c'])
list(dict1.keys())['a', 'b', 'c']
dict1.values()dict_values([1, 2, 3])
list(dict1.values())[1, 2, 3]
dict1.items()dict_items([('a', 1), ('b', 2), ('c', 3)])
d2=dict(apples=1,oranges=2,pears=2)
ud=dict(pears=4,grapes=5,lemons=6)
d2.update(ud)
d2{'apples': 1, 'oranges': 2, 'pears': 4, 'grapes': 5, 'lemons': 6}
dict1{'a': 1, 'b': 2, 'c': 3}
dict2=dict1.copy()
dict2.clear()
dict1{'a': 1, 'b': 2, 'c': 3}
dict2=dict1
dict2.clear()
dict1{}
# elements of set should be immutable!
list1=[[1,2],[3,4]]
set(list1)TypeError: unhashable type: 'list'
list2=[(1,2),(3,4)]
set(list2){(1, 2), (3, 4)}
# if elements are not unique, automatically remove duplicates
list3=[1,2,2,3,4]
set(list3){1, 2, 3, 4}
dict1=dict(a=1,b=2,c=3)
set(dict1){'a', 'b', 'c'}
set(dict1.keys()){'a', 'b', 'c'}
set(dict1.values()){1, 2, 3}
set(dict1.items()){('a', 1), ('b', 2), ('c', 3)}
import copy as cpA=dict(a=1,b=2,c=[1,2,3])
B=A.copy()
C=cp.deepcopy(A)
B['a']=9
B['c'][0]=9
print(A,B,C,sep='\n'){'a': 1, 'b': 2, 'c': [9, 2, 3]}
{'a': 9, 'b': 2, 'c': [9, 2, 3]}
{'a': 1, 'b': 2, 'c': [1, 2, 3]}