<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>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Python 字符串 > 原文: [https://www.programiz.com/python-programming/string](https://www.programiz.com/python-programming/string) #### 在本教程中,您將學習在 Python 中創建,格式化,修改和刪除字符串。 此外,還將向您介紹各種字符串操作和函數。 ## Python 中的字符串是什么? 字符串是字符序列。 字符只是一個符號。 例如,英語具有 26 個字符。 計算機不處理字符,它們處理數字(二進制??)。 即使您可能在屏幕上看到字符,它在內部也會作為 0 和 1 的組合進行存儲和操作。 字符到數字的這種轉換稱為編碼,而相反的過程是解碼。 ASCII 和 Unicode 是一些常用的編碼。 在 Python 中,字符串是 Unicode 字符序列。 引入 Unicode 是為了包括所有語言的每個字符并帶來統一的編碼。 您可以從 [Python Unicode](http://docs.python.org/3.3/howto/unicode.html) 了解 Unicode。 * * * ## 如何在 Python 中創建字符串? 可以通過將字符括在單引號或雙引號中來創建字符串。 Python 中甚至可以使用三引號,但通常用于表示多行字符串和文檔字符串。 ```py # defining strings in Python # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string) ``` 運行該程序時,輸出為: ```py Hello Hello Hello Hello, welcome to the world of Python ``` * * * ## 如何訪問字符串中的字符? 我們可以使用索引訪問單個字符,并使用切片訪問一系列字符。 索引從 0 開始。嘗試訪問超出索引范圍的字符將引發`IndexError`。 索引必須是整數。 我們不能使用浮點數或其他類型,這將導致`TypeError`。 Python 允許對其序列進行負索引。 `-1`的索引指的是最后一項,`-2`的索引指的是倒數第二項,依此類推。 我們可以使用切片運算符`:`(冒號)訪問字符串中的一系列項目。 ```py #Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2]) ``` 當我們運行上面的程序時,我們得到以下輸出: ```py str = programiz str[0] = p str[-1] = z str[1:5] = rogr str[5:-2] = am ``` 如果嘗試訪問超出范圍的索引或使用非整數的數字,則會出現錯誤。 ```py # index must be in range >>> my_string[15] ... IndexError: string index out of range # index must be an integer >>> my_string[1.5] ... TypeError: string indices must be integers ``` 通過考慮索引位于元素之間,可以最好地可視化切片,如下所示。 如果要訪問范圍,則需要索引,該索引將從字符串中切出一部分。 ![Element Slicing in Python](https://img.kancloud.cn/c6/71/c67167494338df35b337599dacf6a127_376x119.png "Element Slicing") Python 中的字符串切片 * * * ## 如何更改或刪除字符串? 字符串是不可變的。 這意味著字符串的元素一旦分配就無法更改。 我們可以簡單地將不同的字符串重新分配給相同的名稱。 ```py >>> my_string = 'programiz' >>> my_string[5] = 'a' ... TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python' ``` 我們無法刪除或刪除字符串中的字符。 但是可以使用`del`關鍵字完全刪除字符串。 ```py >>> del my_string[1] ... TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string ... NameError: name 'my_string' is not defined ``` * * * ## Python 字符串操作 字符串可以執行許多操作,這使它成為 Python 中最常用的數據類型之一。 要了解有關 Python 中可用數據類型的更多信息,請訪問: [Python 數據類型](/python-programming/variables-datatypes) ### 兩個或多個字符串的連接 將兩個或多個字符串連接為單個字符串稱為連接。 `+`運算符在 Python 中執行此操作。 只需將兩個字符串字面值一起寫就可以將它們連接在一起。 `*`運算符可用于將字符串重復給定的次數。 ```py # Python String Operations str1 = 'Hello' str2 ='World!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3) ``` 當我們運行程序時,我們得到以下輸出: ```py str1 + str2 = HelloWorld! str1 * 3 = HelloHelloHello ``` 一起編寫兩個字符串字面值也將它們連接起來,就像`+`運算符一樣。 如果要在不同行中連接字符串,可以使用括號。 ```py >>> # two string literals together >>> 'Hello ''World!' 'Hello World!' >>> # using parentheses >>> s = ('Hello ' ... 'World') >>> s 'Hello World' ``` * * * ### 遍歷字符串 我們可以使用[循環](/python-programming/for-loop)遍歷字符串。 這是一個計算字符串中`l`數量的示例。 ```py # Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found') ``` 當我們運行程序時,我們得到以下輸出: ```py 3 letters found ``` * * * ### 字符串成員資格測試 我們可以使用關鍵字`in`來測試字符串中是否存在子字符串。 ```py >>> 'a' in 'program' True >>> 'at' not in 'battle' False ``` * * * ### 可與字符串一起使用的內置函數 各種與序列一起使用的內置函數也可以與字符串一起使用。 一些常用的是`enumerate()`和`len()`。`enumerate()`函數返回一個枚舉對象。 它包含成對的字符串中所有項目的索引和值。 這對于迭代很有用。 同樣,`len()`返回字符串的長度(字符數)。 ```py str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str)) ``` 當我們運行程序時,我們得到以下輸出: ```py list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')] len(str) = 4 ``` * * * ## Python 字符串格式化 ### 轉義序列 如果我們要打印類似的字面值,`He said, "What's there?"`,我們不能使用單引號或雙引號。 由于文本本身包含單引號和雙引號,因此將導致出現`SyntaxError`。 ```py >>> print("He said, "What's there?"") ... SyntaxError: invalid syntax >>> print('He said, "What's there?"') ... SyntaxError: invalid syntax ``` 解決此問題的一種方法是使用三引號。 另外,我們可以使用轉義序列。 轉義序列以反斜杠開頭,并且以不同的方式解釋。 如果我們使用單引號表示字符串,則必須對字符串內的所有單引號進行轉義。 雙引號也是如此。 這是代表上述文本的方法。 ```py # using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What\'s there?"') # escaping double quotes print("He said, \"What's there?\"") ``` 當我們運行程序時,我們得到以下輸出: ```py He said, "What's there?" He said, "What's there?" He said, "What's there?" ``` 這是 Python 支持的所有轉義序列的列表。 | 轉義序列 | 描述 | | --- | --- | | `\n` | 換行 | | `\\` | 反斜杠 | | `\'` | 單引號 | | `\"` | 雙引號 | | `\a` | ASCII 鈴聲 | | `\b` | ASCII 退格 | | `\f` | ASCII 換頁 | | `\n` | ASCII 換行 | | `\r` | ASCII 回車 | | `\t` | ASCII 水平制表 | | `\v` | ASCII 垂直制表 | | `\ooo` | 具有八進制值的字符 | | `\xHH` | 十六進制值為`HH`的字符 | 這里有些例子 ```py >>> print("C:\\Python32\\Lib") C:\Python32\Lib >>> print("This is printed\nin two lines") This is printed in two lines >>> print("This is \x48\x45\x58 representation") This is HEX representation ``` * * * ### 原始字符串忽略轉義序列 有時我們可能希望忽略字符串中的轉義序列。 為此,我們可以將`r`或`R`放在字符串前面。 這意味著它是一個原始字符串,并且其中的任何轉義序列都將被忽略。 ```py >>> print("This is \x61 \ngood example") This is a good example >>> print(r"This is \x61 \ngood example") This is \x61 \ngood example ``` * * * ### 格式化字符串的`format()`方法 字符串對象可用的`format()`方法在格式化字符串方面非常通用且功能強大。 格式字符串包含大括號`{}`作為占位符或將被替換的替換字段。 我們可以使用位置參數或關鍵字參數來指定順序。 ```py # Python string format() method # default(implicit) order default_order = "{}, {} and {}".format('John','Bill','Sean') print('\n--- Default Order ---') print(default_order) # order using positional argument positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('\n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean') print('\n--- Keyword Order ---') print(keyword_order) ``` 當我們運行程序時,我們得到以下輸出: ```py --- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John ``` `format()`方法可以具有可選的格式規范。 它們使用冒號與字段名稱分隔。 例如,我們可以在給定的空間中將字符串`<`左對齊,`>`右對齊或將`^`居中對齊。 我們還可以將整數格式化為二進制,十六進制等,并且浮點數可以四舍五入或以指數格式顯示。 您可以使用大量的格式。 請訪問此處,以獲取`[format()](/python-programming/methods/string/format)`方法可用的所有[字符串格式。](/python-programming/methods/string/format) ```py >>> # formatting integers >>> "Binary representation of {0} is {0:b}".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: {0:e}".format(1566.345) 'Exponent representation: 1.566345e+03' >>> # round off >>> "One third is: {0:.3f}".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham') '|butter | bread | ham|' ``` * * * ### 舊式格式化 我們甚至可以格式化字符串,例如 C 編程語言中使用的舊`sprintf()`樣式。 我們使用`%`運算符來完成此操作。 ```py >>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457 ``` * * * ## 常見的 Python 字符串方法 字符串對象有許多可用的方法。 我們上面提到的`format()`方法就是其中之一。 某些常用的方法是`lower()`,`upper()`,`join()`,`split()`,`find()`和`replace()`等。這是所有 [Python 中的字符串的內置方法的完整列表](/python-programming/methods/string)。 ```py >>> "PrOgRaMiZ".lower() 'programiz' >>> "PrOgRaMiZ".upper() 'PROGRAMIZ' >>> "This will split all words into a list".split() ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list'] >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string']) 'This will join all words into a string' >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year' ```
                  <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>

                              哎呀哎呀视频在线观看