Python 是一種跨平台的計算機程式設計語言,是一個高層次的結合了解釋性、編譯性、互動性和面向對象的腳本語言。在部落格中,我將陸續記錄我的 Python 學習過程,這是第一篇,Python 3 學習記錄(一):字串。
一、程式碼及呈現#
程式碼:
# 輸出字串
message = "Hello Python!"
print(message)
message2 = "Hello Python 2!"
print(message2)
# 字串大小寫修改
name = "chiloh wei"
print(name.title()) # 首字母大寫
print(name.upper()) # 字母全部大寫
print(name.lower()) # 字母全部小寫
# 字串合併(拼接)
firstname = "chiloh"
lastname = "wei"
fullname = firstname + " " + lastname
print(fullname)
print("Hello," + fullname.title() + "!")
# 制表符/換行符
print("chiloh wei")
print("\tchiloh wei") # 制表符: \t
print("hello,\nchiloh wei!") # 換行符: \n
print("Name:\n\tchiloh wei\n\tchiloh wei 2\n\tchiloh wei 3")
# 刪除空白
text = " https://www.chiloh.cn/ "
website = text.rstrip() # 刪除字串後面空白
website2 = text.lstrip() # 刪除字串前面空白
website3 = text.strip() # 刪除字串兩端空白
print(website)
print(website2)
print(website3)
呈現:
二、課後練習題#
題目一:
將使用者的姓名存到一個變數中,並向該使用者顯示一條訊息。顯示的訊息應非常簡單,如:"Hello Eric, would you like to learn some Python today?"。
程式碼實現:
name = "Eric"
message = "Hello " + name.title() + ", would you like to learn some Python today?"
print(message)
題目二:
將一個人名存儲到一個變數中,再以小寫、大寫和首字母大寫的方式顯示這個人名。
程式碼實現:
myname = "chiloh wei"
print(myname.lower()) # 人名小寫
print(myname.upper()) # 人名大寫
print(myname.title()) # 人名首字母大寫
題目三:
找一句你欽佩的名人名言,將這個名人的姓名和他的名言打印出來。輸出應類似於下面這樣(包括引號):
Albert Einstein once said, "A person who never made a mistake never tried anything new."
程式碼實現:
person = "Albert Einstein"
print(person.title() + 'once said, "A person who never made a mistake never tried anything new."')
題目四:
重複題目三,但將名人的姓名存儲在變數
famous_person
中,再創建要顯示的訊息,並將其存儲在變數message
中,然後打印這條訊息。
程式碼實現:
famous_person = "Albert Einstein"
message = famous_person.title() + 'once said, "A person who never made a mistake never tried anything new."'
print(message)
題目五:
存儲一個人名,並在其開頭和末尾都包含一些空白字元,務必至少使用字元組合 “\t” 和 “\n” 各一次。打印這個人名,以顯示其開頭和末尾的空白。然後,分別使用剔除函數
lstrip()
、rstrip()
和strip()
對人名進行處理,並將結果打印出來。
程式碼實現:
person_name = "\tHis Name:\n\t\tSteven Paul Jobs\n"
print(person_name)
print(person_name.lstrip()) # 剔除開頭空白
print(person_name.rstrip()) # 剔除末尾空白
print(person_name.strip()) # 剔除兩端空白