本文實例講述了Python學習筆記之字符串和字符串方法。分享給大家供大家參考,具體如下:
字符串
在 python 中,字符串的變量類型顯示為
str
。你可以使用雙引號
"
或單引號
'
定義字符串
定義字符串
my_string = 'this is a string!' my_string2 = "this is also a string!!!" # Also , we can use backslash '/' to escape quotes. this_string = 'Simon\'s skateboard is in the garage.' print(this_string)
字符串的常用操作
first_word = 'Hello' second_word = 'There' print(first_word + second_word) # HelloThere print(first_word + ' ' + second_word) # Hello There print(first_word * 5) # HelloHelloHelloHelloHello print(len(first_word)) # 5 print(first_word[0]) # H print(first_word[1]) # e
字符串[相關練習]
在字符串中正確的使用引號
ford_quote = 'Whether you think you can, or you think you can\'t--you\'re right.' print(ford_quote) # Whether you think you can, or you think you can't--you're right.
下面這段代碼的輸出是什么?
coconut_count = "34" mango_count = "15" tropical_fruit_count = coconut_count + mango_count print(tropical_fruit_count) # 3415 (并且 tropical_fruit_count 是字符串)
編寫服務器日志消息
username = "Kinari" timestamp = "04:50" url = "http://petshop.com/pets/mammals/cats" # TODO: print a log message using the variables above. The message should have the same format as this one: "Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20." print(username + ' accessed the site ' + url + ' at ' + timestamp + '.')
使用字符串連接和
len
函數計算某些電影明星的實際完整姓名的長度
given_name = "William" middle_names = "Bradley" family_name = "Pitt" name_length = len(given_name + ' ' + middle_names + ' ' + family_name) # Now we check to make sure that the name fits within the driving license character limit driving_license_character_limit = 28 print(name_length <= driving_license_character_limit) # True
我們剛剛使用函數
len
計算出字符串的長度。當我們向其提供整數 835 而不是字符串時,函數
len
會返回什么?
Error
字符串方法
python 中的方法和函數相似,但是它針對的是你已經創建的變量。方法特定于存儲在特定變量中的數據類型。
每個方法都接受字符串本身作為該方法的第一個參數。但是,它們還可以接收其他參數。我們來看看幾個示例的輸出。
my_string = "sebastian thrun" my_string.islower() # True my_string.count('a') # 2 my_string.find('a') # 3
可以看出,
count
和
find
方法都接受另一個參數。但是,
islower
方法不接受參數。如果我們要在變量中存儲浮點數、整數或其他類型的數據,可用的方法可能完全不同!
字符串方法[相關練習]
-
對浮點型對象調用
islower
等方法會發生什么?例如13.37.islower()
-
會出現錯誤, 方法
islower
屬于字符串方法,而不是浮點數方法。不同類型的對象具有特定于該類型的方法。例如,浮點數具有is_integer
方法,而字符串沒有。 - 練習字符串方法
my_name = "my name is Joh." cap = my_name.capitalize() print(cap) # My name is joh. ew = my_name.endswith('li') print(ew) # False ind = my_name.index('is') print(ind) # 8
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python數據結構與算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
