ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[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测试开发圈”,了解更多测试教程!***