Python學習筆記(一)—— 字串
阿新 • • 發佈:2019-02-12
(1)在python中,字串可以用雙引號或單引號括起來。例如:
str1 = "This is a string."
str2 = 'This is also a string.'
print (str1)
print (str2)
注意:雙引號中可以包含單引號,單引號中也可以包含雙引號。如:
str1 = 'I told my friend, "Python is my favorate language!"'
str2 = "It's beautiful"
(2)修改字串的大小寫。
name = "ada's Face" print (name.upper()) #upper()函式將字串改為大寫 print (name.lower()) #lower()函式將字串改為小寫 print (name.title()) #title()函式將每個單詞的首字母改為大寫
輸出結果為:
ADA'S FACE
ada's face
Ada'S Face
(3)合併字串,使用“+”連線。
first_str = "hello"
last_str = "world"
print (first_str+" "+last_str) #pyhton中使用加號(+)合併字串
輸出結果為:
hello world
(4)刪除字串中的空白。
test_str = ' python ' do_str1 = test_str.rstrip() #rstrip()函式去除字串末尾的空白 do_str2 = test_str.lstrip() #lstrip()函式去除字串開頭的空白 do_str3 = test_str.strip() #strip()函式同時去除字串兩端的空白 print (do_str1) print (do_str2) print (do_str3)
輸出結果為:
python
python
python
(5)使用str()函式將非字串值表示為字串。
age = 23
message = "happy "+str(age)+"rd Birthday!" #str()函式將非字串值表示為字串
print (message)
輸出結果為:
happy 23rd Birthday!