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

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                >[info] 程序的80%時間在處理字符串 > [TOC] <br> ### 字符串定義 字符串可以被單引號,雙引號,三引號包含起來,如 ```python # 字符串定義 name = 'Milton Guan' address = "Guanzhou,China" intro = """ Hello,My name is Milton,I'm from China. I am a student. Nice to meet you. """ # 打印輸出字符串 print(name) print(address) print(intro) ``` `單引號`和`雙引號`沒有什么區別,但是要注意首尾封閉。 `三引號`包含的字符串,可以換行,并且將換行包含在字符串之中,這在需要`格式化`輸出時特別好用哦。 以上字符串的輸出結果如: ``` Milton Guan Guanzhou,China Hello,My name is Milton,I'm from China. I am a student. Nice to meet you. ``` ### 字符串的常用方法 *** ```python def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" ``` #### capitalize():將字符串首字母大寫,其余字母小寫 ```cmd >>> astr="i love China" >>> astr.capitalize() 'I love china' ``` *** ```python def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" ``` #### center():將字符串居中顯示 如果字符串寬度不足,用指定字符填充 ```cmd >>> astr="i love China" >>> astr.center(50,"*") '*******************i love China*******************' ``` *** ```python def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 ``` #### count():統計字符串中包含特定子串的個數 ```cmd >>> astr="i love China,i love Guanzhou" >>> astr.count("love") 2 >>> astr.count("China") 1 ``` *** ```python def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" ``` #### encode():字符串編碼 默認utf-8,返回字節bytes類型 ```cmd >>> astr="i love China,i love Guanzhou" >>> astr 'i love China,i love Guanzhou' >>> astr.encode('utf-8') b'i love China,i love Guanzhou' >>> type(astr) <class 'str'> >>> type(astr.encode('utf-8')) <class 'bytes'> >>> ``` *** ```python def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False ``` #### endswith():判斷字符串是否以某字符串為結尾 #### startswith():判斷字符串是否以某字符串為開頭 返回True或False ```cmd >>> astr="i love China,i love Guanzhou" >>> astr.endswith("Guanzhou") True >>> astr.endswith("China") False >>> >>> astr.startswith("i") True >>> astr.startswith("you") False >>> ``` *** ```python def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 ``` #### find():尋找子串首次出現的位置 位置索引從0開始,尋找失敗,返回-1 ```cmd >>> astr="i love China,i love Guanzhou" >>> astr.find("o") 3 >>> astr.find("w") -1 ``` *** ```python def format(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass ``` #### format():字符串格式化 1. 字符串中可以已參數位置占位 2. 字符串中可以已參數名占位 ```cmd >>> astr="i love {},i love {}".format("China","Guanzhou") >>> astr 'i love China,i love Guanzhou' >>> >>> astr="i love {country},i love {city}".format(city="Guanzhou",country="China") >>> astr 'i love China,i love Guanzhou' >>> ``` *** ```python def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return "" ``` #### format_map():字符串格式化 ```cmd >>> "i love {country},i love {city}".format(**{'country':'China','city':'Guanzhou'}) 'i love China,i love Guanzhou' ``` *** ```python def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 ``` #### index():查找子串位置 類似find(),但是find找不到會返回-1,而index如果找不到會拋出異常 ```cmd >>> astr="i love China,i love Guanzhou" >>> astr.index('love') 2 >>> astr.index('beijing') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> ``` *** ```python def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" ``` #### join():將一個迭代對象連接成字符串 連接符便是當前字符串 ```cmd >>> '-'.join(["Milton","Cherish"]) 'Milton-Cherish' >>> >>> '&&'.join(["Milton","Cherish"]) 'Milton&&Cherish' >>> ``` *** ```python def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" ``` #### ljust():左對齊,rjust():右對齊 默認以空格填充,可以指定填充字符 ```cmd >>> astr="I love China" >>> astr.ljust(50) 'I love China ' >>> astr.ljust(50,"*") 'I love China**************************************' >>> astr.rjust(50,"*") '**************************************I love China' ``` *** ```python def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" ``` #### lower():將字符轉成小寫,upper():將字符轉成大寫,swapcase():大小寫互換 ```cmd >>> astr="I love China" >>> astr.lower() 'i love china' >>> astr.upper() 'I LOVE CHINA' >>> astr.swapcase() 'i LOVE cHINA' >>> ``` *** ```python def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass ``` #### partition():將字符串分差成三元元組 包含匹配字符前面的內容,匹配字符,匹配字符后面的內容 ```cmd >>> astr="I love China" >>> astr.partition("love") ('I ', 'love', ' China') >>> >>> astr.partition("look") ('I love China', '', '') >>> ``` *** ```python def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" ``` #### replace():替換字符串 ```cmd >>> astr="I love China,I love Guanzhou" >>> astr.replace("love","like") 'I like China,I like Guanzhou' >>> astr.replace("love","like",1) 'I like China,I love Guanzhou' ``` *** ```python def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] ``` #### split():用特定的分割符將字符串分割成列表 ```cmd >>> astr="I love China,I love Guanzhou" >>> astr.split(" ") ['I', 'love', 'China,I', 'love', 'Guanzhou'] >>> astr="I-love-China" >>> astr.split("-") ['I', 'love', 'China'] >>> ``` *** ```python def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] ``` #### splitlines():通過換行符,將字符串分割成列表 換行符:`\r`,`\r\n`,`\n` ```cmd >>> astr="I love China,\nI\r\nlove\rGuanzhou" >>> astr.splitlines() ['I love China,', 'I', 'love', 'Guanzhou'] ``` *** ```python def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" ``` #### strip():移除首尾特定字符 lstrip():移除左側特定字符;rstrip():移除右側特定字符 不指定移除字符,默認移除空格 ```cmd >>> astr=" i love China " >>> astr.strip() 'i love China' >>> astr.lstrip() 'i love China ' >>> astr.rstrip() ' i love China' >>> astr="**i love China " >>> astr.lstrip("*").rstrip() 'i love China' >>> ``` *** ```python def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" ``` #### zfill():字符串前面填充‘0’ ```cmd >>> anum="9" >>> "9".zfill(1) '9' >>> "9".zfill(2) '09' >>> "-9".zfill(2) '-9' >>> "-9".zfill(3) '-09' >>> ``` *** #### %s 字符串格式化 字符串格式除了上面的format內置函數外,也可以使用 `%s` 占位符格式化,如 ```cmd >>> "My name is %s,I am %s years old" %("Milton",18) 'My name is Milton,I am 18 years old' ``` 建議使用format格式化,format是比較新的函數,而%s舊式的格式化最終會從該語言中移除 <hr style="margin-top:100px"> :-: ![](https://box.kancloud.cn/2ff0bc02ec938fef8b6dd7b7f16ee11d_258x258.jpg) ***微信掃一掃,關注“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>

                              哎呀哎呀视频在线观看