<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Python 字符串 > 原文: [https://thepythonguru.com/python-strings/](https://thepythonguru.com/python-strings/) * * * 于 2020 年 1 月 10 日更新 * * * python 中的字符串是由單引號或雙引號分隔的連續字符系列。 Python 沒有任何單獨的字符數據類型,因此它們表示為單個字符串。 ## 創建字符串 * * * ```py >>> name = "tom" # a string >>> mychar = 'a' # a character ``` 您還可以使用以下語法創建字符串。 ```py >>> name1 = str() # this will create empty string object >>> name2 = str("newstring") # string object containing 'newstring' ``` ```py name = "tom" # a string mychar = 'a' # a character print(name) print(mychar) name1 = str() # this will create empty string object name2 = str("newstring") # string object containing 'newstring' print(name1) print(name2) ``` ## Python 中的字符串是不可變的 * * * 這對您而言意味著,一旦創建了字符串,便無法對其進行修改。 讓我們以一個例子來說明這一點。 ```py >>> str1 = "welcome" >>> str2 = "welcome" ``` 這里`str1`和`str2`指的是存儲在內存中某個位置的相同字符串對象“`welcome`”。 您可以使用[`id()`](/python-builtin-functions/id/)函數測試`str1`是否與`str2`引用相同的對象。 什么是身份證? python 中的每個對象都存儲在內存中的某個位置。 我們可以使用`id()`獲得該內存地址。 ```py >>> id(str1) 78965411 >>> id(str2) 78965411 ``` 由于`str1`和`str2`都指向相同的存儲位置,因此它們都指向同一對象。 讓我們嘗試通過向其添加新字符串來修改`str1`對象。 ```py >>> str1 += " mike" >>> str1 welcome mike >>> id(str1) >>>?78965579 ``` 如您現在所見,`str1`指向完全不同的內存位置,這證明了并置不會修改原始字符串對象而是創建一個新的字符串對象這一點。 同樣,數字(即`int`類型)也是不可變的。 試試看: ```py str1 = "welcome" str2 = "welcome" print(id(str1), id(str2)) str1 += " mike" print(str1) print(id(str1)) ``` ## 字符串操作 * * * 字符串索引從`0`開始,因此要訪問字符串類型中的第一個字符: ```py >>> name[0] # t ``` 試一試: ```py name = "tom" print(name[0]) print(name[1]) ``` `+`運算符用于連接字符串,而`*`運算符是字符串的重復運算符。 ```py >>> s = "tom and " + "jerry" >>> print(s) tom and jerry ``` ```py >>> s = "spamming is bad " * 3 >>> print(s) 'spamming is bad spamming is bad spamming is bad ' ``` 試一試: ```py s = "tom and " + "jerry" print(s) s = "spamming is bad " * 3 print(s) ``` ## 字符串切片 * * * 您可以使用`[]`運算符(也稱為切片運算符)從原始字符串中提取字符串的子集。 **語法**:`s[start:end]` 這將從索引`start`到索引`end - 1`返回字符串的一部分。 讓我們舉一些例子。 ```py >>> s = "Welcome" >>> s[1:3] el ``` 一些更多的例子。 ```py >>> s = "Welcome" >>> >>> s[:6] 'Welcom' >>> >>> s[4:] 'ome' >>> >>> s[1:-1] 'elcom' ``` 試一試: ```py s = "Welcome" print(s[1:3]) print(s[:6]) print(s[4:]) print(s[1:-1]) ``` **注意**: `start`索引和`end`索引是可選的。 如果省略,則`start`索引的默認值為`0`,而`end`的默認值為字符串的最后一個索引。 ## `ord()`和`chr()`函數 * * * `ord()`-函數返回字符的 ASCII 碼。 `chr()`-函數返回由 ASCII 數字表示的字符。 ```py >>> ch = 'b' >>> ord(ch) 98 >>> chr(97) 'a' >>> ord('A') 65 ``` 試一試: ```py ch = 'b' print(ord(ch)) print(chr(97)) print(ord('A')) ``` ## Python 中的字符串函數 * * * | 函數名稱 | 函數說明 | | --- | --- | | `len ()` | 返回字符串的長度 | | `max()` | 返回具有最高 ASCII 值的字符 | | `min()` | 返回具有最低 ASCII 值的字符 | ```py >>> len("hello") 5 >>> max("abc") 'c' >>> min("abc") 'a' ``` 試一試: ```py print(len("hello")) print(max("abc")) print(min("abc")) ``` ## `in`和`not in`運算符 * * * 您可以使用`in`和`not in`運算符檢查另一個字符串中是否存在一個字符串。 他們也被稱為會員運營商。 ```py >>> s1 = "Welcome" >>> "come" in s1 True >>> "come" not in s1 False >>> ``` 試一試: ```py s1 = "Welcome" print("come" in s1) print("come" not in s1) ``` ## 字符串比較 * * * 您可以使用[`>`,`<`,`<=`,`<=`,`==`,`!=`)比較兩個字符串。 Python 按字典順序比較字符串,即使用字符的 ASCII 值。 假設您將`str1`設置為`"Mary"`并將`str2`設置為`"Mac"`。 比較`str1`和`str2`的前兩個字符(`M`和`M`)。 由于它們相等,因此比較后兩個字符。 因為它們也相等,所以比較了前兩個字符(`r`和`c`)。 并且因為`r`具有比`c`更大的 ASCII 值,所以`str1`大于`str2`。 這里還有更多示例: ```py >>> "tim" == "tie" False >>> "free" != "freedom" True >>> "arrow" > "aron" True >>> "right" >= "left" True >>> "teeth" < "tee" False >>> "yellow" <= "fellow" False >>> "abc" > "" True >>> ``` 試一試: ```py print("tim" == "tie") print("free" != "freedom") print("arrow" > "aron") print("right" >= "left") print("teeth" < "tee") print("yellow" <= "fellow") print("abc" > "") ``` ## 使用`for`循環迭代字符串 * * * 字符串是一種序列類型,也可以使用`for`循環進行迭代(要了解有關`for`循環的更多信息,[請單擊此處](/python-loops/))。 ```py >>> s = "hello" >>> for i in s: ... print(i, end="") hello ``` **注意**: 默認情況下,`print()`函數用換行符打印字符串,我們通過傳遞名為`end`的命名關鍵字參數來更改此行為,如下所示。 ```py print("my string", end="\n") # this is default behavior print("my string", end="") # print string without a newline print("my string", end="foo") # now print() will print foo after every string ``` 試一試: ```py s = "hello" for i in s: print(i, end="") ``` ## 測試字符串 * * * python 中的字符串類具有各種內置方法,可用于檢查不同類型的字符串。 | 方法名稱 | 方法說明 | | --- | --- | | `isalnum()` | 如果字符串是字母數字,則返回`True` | | `isalpha()` | 如果字符串僅包含字母,則返回`True` | | `isdigit()` | 如果字符串僅包含數字,則返回`True` | | `isidentifier()` | 返回`True`是字符串是有效的標識符 | | `islower()` | 如果字符串為小寫,則返回`True` | | `isupper()` | 如果字符串為大寫則返回`True` | | `isspace()` | 如果字符串僅包含空格,則返回`True` | ```py >>> s = "welcome to python" >>> s.isalnum() False >>> "Welcome".isalpha() True >>> "2012".isdigit() True >>> "first Number".isidentifier() False >>> s.islower() True >>> "WELCOME".isupper() True >>> " \t".isspace() True ``` 試一試: ```py s = "welcome to python" print(s.isalnum()) print("Welcome".isalpha()) print("2012".isdigit()) print("first Number".isidentifier()) print(s.islower()) print("WELCOME".isupper()) print(" \t".isspace()) ``` ## 搜索子串 * * * | 方法名稱 | 方法說明 | | --- | --- | | `endwith(s1: str): bool` | 如果字符串以子字符串`s1`結尾,則返回`True` | | `startswith(s1: str): bool` | 如果字符串以子字符串`s1`開頭,則返回`True` | | `count(s: str): int` | 返回字符串中子字符串出現的次數 | | `find(s1): int` | 返回字符串中`s1`起始處的最低索引,如果找不到字符串則返回`-1` | | `rfind(s1): int` | 從字符串中`s1`的起始位置返回最高索引,如果找不到字符串則返回`-1` | ```py >>> s = "welcome to python" >>> s.endswith("thon") True >>> s.startswith("good") False >>> s.find("come") 3 >>> s.find("become") -1 >>> s.rfind("o") 15 >>> s.count("o") 3 >>> ``` 試一試: ```py s = "welcome to python" print(s.endswith("thon")) print(s.startswith("good")) print(s.find("come")) print(s.find("become")) print(s.rfind("o")) print(s.count("o")) ``` ## 轉換字符串 * * * | 方法名稱 | 方法說明 | | --- | --- | | `capitalize(): str` | 返回此字符串的副本,僅第一個字符大寫。 | | `lower(): str` | 通過將每個字符轉換為小寫來返回字符串 | | `upper(): str` | 通過將每個字符轉換為大寫來返回字符串 | | `title(): str` | 此函數通過大寫字符串中每個單詞的首字母來返回字符串 | | `swapcase(): str` | 返回一個字符串,其中小寫字母轉換為大寫,大寫字母轉換為小寫 | | `replace(old, new): str` | 此函數通過用新字符串替換舊字符串的出現來返回新字符串 | ```py s = "string in python" >>> >>> s1 = s.capitalize() >>> s1 'String in python' >>> >>> s2 = s.title() >>> s2 'String In Python' >>> >>> s = "This Is Test" >>> s3 = s.lower() >>> s3 'this is test' >>> >>> s4 = s.upper() >>> s4 'THIS IS TEST' >>> >>> s5 = s.swapcase() >>> s5 'tHIS iS tEST' >>> >>> s6 = s.replace("Is", "Was") >>> s6 'This Was Test' >>> >>> s 'This Is Test' >>> ``` 試一試: ```py s = "string in python" s1 = s.capitalize() print(s1) s2 = s.title() print(s2) s = "This Is Test" s3 = s.lower() print(s3) s4 = s.upper() print(s4) s5 = s.swapcase() print(s5) s6 = s.replace("Is", "Was") print(s6) print(s) ``` 在下一章中,我們將學習 python 列表 * * * * * *
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看