視頻位置:138:40
字典
用大括號定義字典。{}
customer = {
"name":"John Smith",
"age":30,
"is_verified":True
}
print(customer["name"])
輸出爲:
John Smith
如果是沒有的值會提示出錯。區分大小寫。
customer = {
"name":"John Smith",
"age":30,
"is_verified":True
}
print(customer["Name"]) #此處N大寫了
會提示:
print(customer["Name"])
KeyError: 'Name'
可以用get功能,防止程序報錯。
customer = {
"name":"John Smith",
"age":30,
"is_verified":True
}
print(customer.get("Name")) #此處N大寫了
print(customer.get("age"))
輸出爲:
None
30
get也可以賦值
customer = {
"name":"John Smith",
"age":30,
"is_verified":True
}
print(customer.get("birthdate","Jan 1 1980")) #沒有的會賦值
print(customer.get("age","Jan 1 1980")) #有的不會變
print(customer) #上面的birthdate並沒有添加進來
輸出爲:
Jan 1 1980
30
{'name': 'John Smith', 'age': 30, 'is_verified': True}
想要改變內容,可以用等號
customer = {
"name":"John Smith",
"age":30,
"is_verified":True
}
customer["name"] = 'Jack Smith'
customer["birthdate"] = "Jan 1 1980"
print(customer["name"])
print(customer)
輸出爲:
Jack Smith
{'name': 'Jack Smith', 'age': 30, 'is_verified': True, 'birthdate': 'Jan 1 1980'}
小練習:
輸入一串數字如:134
輸出one two four
我的程序:
phone = {
"0":"zero", #注意是冒號
"1":"one",
"2":"two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
}
user_input = input("phone: ")
for item in user_input:
print(phone[item])
輸出爲:
phone: 148
one
four
eight
如果要用get,注意:
print(phone.get(item,"!"))
#print(phone.get([item],"!") 這個不對,沒有中括號
視頻主的程序:
phone = {
"0":"zero",
"1":"one",
"2":"two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
}
user_input = input("phone: ")
output = ""
for item in user_input:
output = output + phone.get(item,"!") + " "
print(output)
輸出爲:
phone: 257t
two five seven !
和我的區別,視頻主把這個輸出用字符串串了起來,且加了空格,輸出爲一行。
split功能
message = input(">")
word = message.split(' ') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內容
print(word)
word1 = message.split('ab') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內容
print(word1)
word2 = message.split('m') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內容
print(word2)
輸出爲:
>si abde cdmaio king
['si', 'abde', 'cdmaio', 'king']
['si ', 'de cdmaio king']
['si abde cd', 'aio king']
替換某些字符串中字符
message = input(">")
words = message.split(' ') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內
emojis = {
":)":"lalalala",
":(":"55555555"
}
output = ""
for word in words:
output += emojis.get(word,word) +" "
print(output)
輸出爲:
>MY name is :( i am happy
MY name is 55555555 i am happy
視頻位置:150:50