99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀復(fù)習(xí)Python中的字符串知識點(diǎn)
復(fù)習(xí)Python中的字符串知識點(diǎn)
2017-08-18
收藏

復(fù)習(xí)Python中的字符串知識點(diǎn)

Python中創(chuàng)建字符串對象非常容易。只要將所需的文本放入一對引號中,就完成了一個新字符串的創(chuàng)建(參見清單 1)。如果稍加思考的話,您可能會感到有些困惑。畢竟,有兩類可以使用的引號:單引號 (') 和雙引號 (")。幸運(yùn)的是,Python 再一次使這種問題迎刃而解。您可以使用任意一類引號來表示 Python 中的字符串,只要引號一致就行。如果字符串是以單引號開始,那么必須以單引號結(jié)束,反之亦然。如果不遵循這一規(guī)則,則會出現(xiàn) SyntaxError 異常。

清單 1. 在 Python 中創(chuàng)建字符串    
>>> sr="Discover Python"
>>> type(sr)

>>> sr='Discover Python'
>>> type(sr)

>>> sr="Discover Python: It's Wonderful!"   
>>> sr='Discover Python"
 File "", line 1
  sr='Discover Python"
            ^
SyntaxError: EOL while scanning single-quoted string
>>> sr="Discover Python: \
... It's Wonderful!"
>>> print sr
Discover Python: It's Wonderful!

從清單 1 中可以看出,除了字符串用適當(dāng)?shù)囊柪ㄆ饋碇?,另外還有兩個重要方面。第一,在創(chuàng)建字符串時,您可以混合使用單引號和雙引號,只要字符串在開始位置和結(jié)束位置使用同一類型的引號。這種靈活性允許 Python 容易地保留常規(guī)的文本數(shù)據(jù),這些常規(guī)的文本數(shù)據(jù)可能需要使用單引號來表示簡寫的動詞形式或所屬關(guān)系,以及使用雙引號來表示引述文本。

第二,如果字符串用一行表示太長,您可以使用 Python 連續(xù)字符:反斜線 (\) 來對字符串進(jìn)行折行。從內(nèi)部機(jī)制看,在創(chuàng)建字符串時換行符會被忽略,在打印字符串時可以看出這一點(diǎn)。您可以結(jié)合使用這兩個功能,來創(chuàng)建包含較長段落的字符串,如清單 2 所示。
清單 2. 創(chuàng)建長字符串    
>>> passage = 'When using the Python programming language, one must proceed \
... with caution. This is because Python is so easy to use and can be so \
... much fun. Failure to follow this warning may lead to shouts of \
... "WooHoo" or "Yowza".'
>>> print passage
When using the Python programming language, one must proceed with caution.
This is because Python is so easy to use, and can be so much fun.
Failure to follow this warning may lead to shouts of "WooHoo" or "Yowza".

編者注:上面的示例已折行處理,這樣使頁面布局更合理。事實(shí)上,它本來顯示為一個較長的行。

注意,當(dāng)打印 passage 字符串時,所有格式將被刪除,只保留一個非常 長的字符串。通常,您可以使用控制符來表示字符串中的簡單格式。例如,要表示一個新行開始,您可以使用換行控制符 (\n);要表示插入一個制表符(預(yù)設(shè)空格數(shù)),可以使用制表符控制符 (\t),如清單 3 所示。
清單 3. 在字符串中使用控制符    
>>> passage='\tWhen using the Python programming language, one must proceed\n\
... \twith caution. This is because Python is so easy to use, and\n\
... \tcan be so much fun. Failure to follow this warning may lead\n\
... \tto shouts of "WooHoo" or "Yowza".'
>>> print passage
    When using the Python programming language, one must proceed
    with caution. This is because Python is so easy to use, and
    can be so much fun. Failure to follow this warning may lead
    to shouts of "WooHoo" or "Yowza".
>>> passage=r'\tWhen using the Python programming language, one must proceed\n\
... \twith caution. This is because Python is so easy to use, and\n\
... \tcan be so much fun. Failure to follow this warning may lead\n\
... \tto shouts of "WooHoo" or "Yowza".'
>>> print passage
\tWhen using the Python programming language, one must proceed\n\
\twith caution. This is because Python is so easy to use, and\n\
\tcan be so much fun. Failure to follow this warning may lead\n\
\tto shouts of "WooHoo" or "Yowza".

清單 3 中的第一段按照您預(yù)期的方式使用了控制符。該段已具備良好的格式,閱讀非常方便。第二個示例雖然也進(jìn)行了格式化處理,但它引用的是所謂的原始字符串,即沒有應(yīng)用控制符的字符串。您始終可以認(rèn)出原始字符串,因為該字符串的起始引號的前面有一個 r 字符,它是 raw 的縮寫。

我不了解您講的有什么可取之處,雖然這種方法可行,但創(chuàng)建一個段落字符串似乎非常因難。當(dāng)然一定有更好的方法。與往常一樣,Python 提供了一種非常簡單的方法用于創(chuàng)建長字符串,該方法可保留創(chuàng)建字符串時所使用的格式。這種方法是使用三個雙引號(或三個單引號)來開始和結(jié)束長字符串。在該字符串中,您可以使用任意多的單引號和雙引號(參見清單 4)。
清單 4. 使用三個引號的字符串
    
>>> passage = """
...     When using the Python programming language, one must proceed
...     with caution. This is because Python is so easy to use, and
...     can be so much fun. Failure to follow this warning may lead
...     to shouts of "WooHoo" or "Yowza".
... """
>>> print passage
         
    When using the Python programming language, one must proceed
    with caution. This is because Python is so easy to use, and
    can be so much fun. Failure to follow this warning may lead
    to shouts of "WooHoo" or "Yowza".

將字符串作為一個對象

如果閱讀了本系列前兩篇文章中的任何一篇文章,那么在您的腦海中會立即浮現(xiàn)出這樣一句話:在 Python 中,所有事物都是對象。到目前為止,我還沒有涉及到關(guān)于 Python 中的字符串的對象特性的問題,但是,與往常一樣,Python 中的字符串就是對象。事實(shí)上,字符串對象是 str 類的一個實(shí)例。正如您在 探索 Python,第 2 部分 中看到的,Python 解釋器包括一個內(nèi)置幫助工具(如清單 5 所示),它可以提供關(guān)于 str 類的信息。
清單 5. 獲取關(guān)于字符串的幫助信息    
>>> help(str)
      
Help on class str in module __builtin__:
           
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
|   str
|   basestring
|   object
|
| Methods defined here:
|
| __add__(...)
|   x.__add__(y) <==> x+y
|
...

使用單引號、雙引號和三引號語法創(chuàng)建的字符串仍然是字符串對象。但是您也可以使用 str 類構(gòu)造函數(shù)顯式地創(chuàng)建字符串對象,如清單 6 所示。該構(gòu)造函數(shù)可以接受簡單的內(nèi)置數(shù)值類型或字符數(shù)據(jù)作為參數(shù)。兩種方法都可以將輸入的內(nèi)容更改為新的字符串對象。
清單 6. 創(chuàng)建字符串    
>>> str("Discover python")
'Discover python'
>>> str(12345)
'12345'
>>> str(123.45)
'123.45'
>>> "Wow," + " that " + "was awesome."
'Wow, that was awesome.'
>>> "Wow,"" that ""was Awesome"
'Wow, that was Awesome'
>>> "Wow! "*5
'Wow! Wow! Wow! Wow! Wow! '
>>> sr = str("Hello ")
>>> id(sr)
5560608
>>> sr += "World"
>>> sr
'Hello World'
>>> id(sr)
3708752

清單 6 中的例子也展示了關(guān)于 Python 字符串的幾個其他重要方面。第一,通過將其他字符串添加在一起,可以創(chuàng)建新的字符串,具體方法可以使用 + 運(yùn)算符,或者干脆使用適當(dāng)?shù)囊枌⒆址B在一起。第二,如果需要重復(fù)短字符串來創(chuàng)建長字符串,可以使用 * 運(yùn)算符,將字符串重復(fù)一定的次數(shù)。我在本文開頭說過,在 Python 中,字符串是不變的字符序列, 上例中的最后幾行說明了這一點(diǎn),我首先創(chuàng)建一個字符串,然后通過添加其他字符串對它進(jìn)行修改。從對 id 方法兩次調(diào)用的輸出中可以看出,創(chuàng)建的新字符串對象中保存的是向原字符串中添加文本的結(jié)果。

str 類包含大量的用于操作字符串的有用方法。這里不做一一介紹,您可以使用幫助解釋器獲得有關(guān)信息?,F(xiàn)在讓我們了解一下四個有用的函數(shù),并演示其他 str 類方法的工具。清單 7 演示了 upper、lower、split 和 join 方法。
清單 7. 字符串方法
    
>>> sr = "Discover Python!"
>>> sr.upper()
'DISCOVER PYTHON!'
>>> sr.lower()
'discover python!'
>>> sr = "This is a test!"
>>> sr.split()
['This', 'is', 'a', 'test!']
>>> sr = '0:1:2:3:4:5:6:7:8:9'
>>> sr.split(':')
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> sr=":"
>>> tp = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
>>> sr.join(tp)
'0:1:2:3:4:5:6:7:8:9'

前兩個方法 upper 和 lower 很容易理解。它們只是分別將字符串都轉(zhuǎn)換成大寫字母或小寫字母。split 方法很有用,因為它可以將一個字符串分成幾個較小的字符串序列,方法是將令牌字符(或給定字符序列中的任何字符)用作斷開位置的指示器。所以,第一個 split 方法示例使用默認(rèn)的令牌將字符串“This is a test”拆分開,此令牌可以是任何空白字符(這個序列包括空格、制表符和換行符)。第二個 split 方法演示如何使用不同的令牌字符(本例中使用的是冒號)將一個字符串分成一系列字符串。最后的一個例子顯示如何使用 join 方法,該方法的作用與 split 方法相反, 可以使多個短字符串序列形成一個長字符串。在本例中,使用冒號將 tuple 包含的由單個字符構(gòu)成的字符串序列連接在一起。

將字符串用作字符的容器

在本文的開頭部分,我著重強(qiáng)調(diào)了 Python 中的字符串是不變的字符序列。本系列的第 2 部分 探索 Python,第 2 部分 介紹了 tuple,它也是一個不變的序列。tuple 通過以下方式支持訪問序列中的元素:使用索引符號,使用片段分離序列中的元素,以及使用特定的片段或?qū)⒉煌钠翁砑釉谝黄饋韯?chuàng)建新的元組。根據(jù)這一情況,您可能想知道是否可以將同一技巧應(yīng)用于 Python 字符串。如清單 8 所示,答案顯然是“可以”。
清單 8. 字符串方法    
>>> sr="0123456789"
>>> sr[0]
'0'
>>> sr[1] + sr[0]  
'10'
>>> sr[4:8]   # Give me elements four through seven, inclusive
'4567'
>>> sr[:-1]   # Give me all elements but the last one
'012345678'
>>> sr[1:12]  # Slice more than you can chew, no problem
'123456789'
>>> sr[:-20]  # Go before the start?
''
>>> sr[12:]   # Go past the end?
''
>>> sr[0] + sr[1:5] + sr[5:9] + sr[9]
'0123456789'
>>> sr[10]
Traceback (most recent call last):
 File "", line 1, in ?
IndexError: string index out of range
>>> len(sr)   # Sequences have common methods, like get my length
10

在 Python 中,將字符串作為字符序列進(jìn)行處理是非常簡單的。您可以獲得單個元素,將不同的元素添加在一起,切出幾個元素,甚至將不同的片段添加在一起。進(jìn)行切片的一個非常有用的特性是,在開始之前或結(jié)束之后進(jìn)行較多切片不會拋出異常,只是相應(yīng)地以默認(rèn)方式開始或結(jié)束該序列。相反,如果您試圖使用允許范圍之外的索引來訪問單個元素,則會得到一個異常。這種行為說明了為什么 len 方法是如此重要。

字符串:功能強(qiáng)大的工具

在本文中,我介紹了Python字符串,它是一種不變的字符序列。在 Python 中,您可以使用多個方法很容易地創(chuàng)建字符串,其中包括使用單引號、雙引號或更靈活的方式,即使用一組三個引號。假設(shè) Python 中的每個事物都是一個對象,您可以使用底層的 str 類方法來獲得附加功能或直接使用字符串的序列功能。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }