💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Python – 字符串 > 原文: [https://howtodoinjava.com/python/python-strings/](https://howtodoinjava.com/python/python-strings/) 在 [Python](https://howtodoinjava.com/python-tutorial/) 中,`string`字面值是: * 代表 Unicode 字符的字节数组 * 用单引号或双引号引起来 * 无限长度 ```py str = 'hello world' str = "hello world" ``` 使用三个单引号或三个双引号创建**多行字符串**。 ```py str = '''Say hello to python programming''' str = """Say hello to python programming""" ``` > Python 没有字符数据类型,单个字符就是长度为 1 的字符串。 ## 2.子串或切片 通过使用切片语法,我们可以获得一系列字符。 索引从零开始。 `str[m:n]`从位置 2(包括)到 5(不包括)返回字符串。 ```py str = 'hello world' print(str[2:5]) # llo ``` **负切片**从末尾返回子字符串。 ```py str = 'hello world' print(str[-5:-2]) # wor ``` `str[-m:-n]`将字符串从位置 -5(不包括)返回到 -2(包括)。 ## 3.字符串作为数组 在 python 中,字符串表现为数组。 方括号可用于访问字符串的元素。 ```py str = 'hello world' print(str[0]) # h print(str[1]) # e print(str[2]) # l print(str[20]) # IndexError: string index out of range ``` ## 4.字符串长度 `len()`函数返回字符串的长度: ```py str = 'hello world' print(len(str)) # 11 ``` ## 5.字符串格式化 要在 python 中格式化字符串,请在所需位置在字符串中使用占位符`{ }`。 将参数传递给`format()`函数以使用值格式化字符串。 我们可以在占位符中传递参数位置(从零开始)。 ```py age = 36 name = 'Lokesh' txt = "My name is {} and my age is {}" print(txt.format(name, age)) # My name is Lokesh and my age is 36 txt = "My age is {1} and the name is {0}" print(txt.format(name, age)) # My age is 36 and the name is Lokesh ``` ## 6.字符串方法 #### 6.1 `capitalize()` 它返回一个字符串,其中给定字符串的第一个字符被转换为大写。 当第一个字符为非字母时,它将返回相同的字符串。 ```py name = 'lokesh gupta' print( name.capitalize() ) # Lokesh gupta txt = '38 yrs old lokesh gupta' print( txt.capitalize() ) # 38 yrs old lokesh gupta ``` #### 6.2 `casefold()` 它返回一个字符串,其中所有字符均为给定字符串的小写字母。 ```py txt = 'My Name is Lokesh Gupta' print( txt.casefold() ) # my name is lokesh gupta ``` #### 6.3 `center()` 使用指定的字符(默认为空格)作为填充字符,使字符串居中对齐。 在给定的示例中,输出总共需要 20 个字符,而“ hello world”位于其中。 ```py txt = "hello world" x = txt.center(20) print(x) # ' hello world ' ``` #### 6.4 `count()` 它返回指定值出现在字符串中的次数。 它有两种形式: `count(value)` - 要在字符串中搜索的`value` `count(value, start, end)` - 要在字符串中搜索的`value`,其中搜索起始于`start`位置,直到`end`位置。 ```py txt = "hello world" print( txt.count("o") ) # 2 print( txt.count("o", 4, 7) ) # 1 ``` #### 6.5 `encode()` 它使用指定的编码对字符串进行编码。 如果未指定编码,将使用`UTF-8`。 ```py txt = "My name is åmber" x = txt.encode() print(x) # b'My name is \xc3\xa5mber' ``` #### 6.6 [`endswith()`](https://howtodoinjava.com/python/string-endswith-method/) 如果字符串以指定值结尾,则返回`True`,否则返回`False`。 ```py txt = "hello world" print( txt.endswith("world") ) # True print( txt.endswith("planet") ) # False ``` #### 6.7 `expandtabs()` 它将制表符大小设置为指定的空格数。 ```py txt = "hello\tworld" print( txt.expandtabs(2) ) # 'hello world' print( txt.expandtabs(4) ) # 'hello world' print( txt.expandtabs(16) ) # 'hello world' ``` #### 6.8 `find()` 它查找指定值的第一次出现。 如果指定的值不在字符串中,则返回`-1`。 `find()`与`index()`方法相同,唯一的区别是,如果找不到该值,则`index()`方法会引发异常。 ```py txt = "My name is Lokesh Gupta" x = txt.find("e") print(x) # 6 ``` #### 6.9 `format()` 它格式化指定的字符串,并在字符串的占位符内插入参数值。 ```py age = 36 name = 'Lokesh' txt = "My name is {} and my age is {}" print( txt.format(name, age) ) # My name is Lokesh and my age is 36 ``` #### 6.10 `format_map()` 它用于返回字典键的值,以格式化带有命名占位符的字符串。 ```py params = {'name':'Lokesh Gupta', 'age':'38'} txt = "My name is {name} and age is {age}" x = txt.format_map(params) print(x) # My name is Lokesh Gupta and age is 38 ``` #### 6.11 `index()` * 它在给定的字符串中查找指定值的第一次出现。 * 如果找不到要搜索的值,则会引发异常。 ```py txt = "My name is Lokesh Gupta" x = txt.index("e") print(x) # 6 x = txt.index("z") # ValueError: substring not found ``` #### 6.12 `isalnum()` 它检查字母数字字符串。 如果所有字符均为字母数字,表示字母`(a-zA-Z)`和数字`(0-9)`,则返回`True`。 ```py print("LokeshGupta".isalnum()) # True print("Lokesh Gupta".isalnum()) # False - Contains space ``` #### 6.13 `isalpha()` 如果所有字符都是字母,则返回`True`,表示字母`(a-zA-Z)`。 ```py print("LokeshGupta".isalpha()) # True print("Lokesh Gupta".isalpha()) # False - Contains space print("LokeshGupta38".isalpha()) # False - Contains numbers ``` #### 6.14 `isdecimal()` 如果所有字符均为十进制(0-9),则返回代码。 否则返回`False`。 ```py print("LokeshGupta".isdecimal()) # False print("12345".isdecimal()) # True print("123.45".isdecimal()) # False - Contains 'point' print("1234 5678".isdecimal()) # False - Contains space ``` #### 6.15 `isdigit()` 如果所有字符都是数字,则返回`True`,否则返回`False`。 指数也被认为是数字。 ```py print("LokeshGupta".isdigit()) # False print("12345".isdigit()) # True print("123.45".isdigit()) # False - contains decimal point print("1234\u00B2".isdigit()) # True - unicode for square 2 ``` #### 6.16 `isidentifier()` 如果字符串是有效的标识符,则返回`True`,否则返回`False`。 有效的标识符仅包含字母数字字母`(a-z)`和`(0-9)`或下划线`( _ )`。 它不能以数字开头或包含任何空格。 ```py print( "Lokesh_Gupta_38".isidentifier() ) # True print( "38_Lokesh_Gupta".isidentifier() ) # False - Start with number print( "_Lokesh_Gupta".isidentifier() ) # True print( "Lokesh Gupta 38".isidentifier() ) # False - Contain spaces ``` #### 6.17 `islower()` 如果所有字符均小写,则返回`True`,否则返回`False`。 不检查数字,符号和空格,仅检查字母字符。 ```py print( "LokeshGupta".islower() ) # False print( "lokeshgupta".islower() ) # True print( "lokesh_gupta".islower() ) # True print( "lokesh_gupta_38".islower() ) # True ``` #### 6.18 `isnumeric()` 如果所有字符都是数字(`0-9`),则此方法返回`True`,否则返回`False`。 指数也被认为是数值。 ```py print("LokeshGupta".isnumeric()) # False print("12345".isnumeric()) # True print("123.45".isnumeric()) # False - contains decimal point print("1234\u00B2".isnumeric()) # True - unicode for square 2 ``` #### 6.19 `isprintable()` 如果所有字符均可打印,则返回`True`,否则返回 False。 不可打印字符用于指示某些格式化操作,例如: * 空格(被视为不可见的图形) * 回车 * 制表 * 换行 * 分页符 * 空字符 ```py print("LokeshGupta".isprintable()) # True print("Lokesh Gupta".isprintable()) # True print("Lokesh\tGupta".isprintable()) # False ``` #### 6.20 `isspace()` 如果字符串中的所有字符都是空格,则返回`True`,否则返回`False`。 #### 6.21 `istitle()` 如果文本中的所有单词均以大写字母开头,而其余单词均为小写字母(即标题大小写),则返回`True`。 否则`False`。 ```py print("Lokesh Gupta".istitle()) # True print("Lokesh gupta".istitle()) # False ``` #### 6.22 `isupper()` 如果所有字符均大写,则返回`True`,否则返回`False`。 不检查数字,符号和空格,仅检查字母字符。 ```py print("LOKESHGUPTA".isupper()) # True print("LOKESH GUPTA".isupper()) # True print("Lokesh Gupta".isupper()) # False ``` #### 6.23 `join()` 它以可迭代方式获取所有项目,并使用强制性指定的分隔符将它们连接为一个字符串。 ```py myTuple = ("Lokesh", "Gupta", "38") x = "#".join(myTuple) print(x) # Lokesh#Gupta#38 ``` #### 6.24 `ljust()` 此方法将使用指定的字符(默认为空格)作为填充字符使字符串左对齐。 ```py txt = "lokesh" x = txt.ljust(20, "-") print(x) # lokesh-------------- ``` #### 6.25 `lower()` 它返回一个字符串,其中所有字符均为小写。 符号和数字将被忽略。 ```py txt = "Lokesh Gupta" x = txt.lower() print(x) # lokesh gupta ``` #### 6.26 `lstrip()` 它删除所有前导字符(默认为空格)。 ```py txt = "#Lokesh Gupta" x = txt.lstrip("#_,.") print(x) # Lokesh Gupta ``` #### 6.27 `maketrans()` 它创建一个字符到其转换/替换的一对一映射。 当在`translate()`方法中使用时,此转换映射用于将字符替换为其映射的字符。 ```py dict = {"a": "123", "b": "456", "c": "789"} string = "abc" print(string.maketrans(dict)) # {97: '123', 98: '456', 99: '789'} ``` #### 6.28 `partition()` 它在给定的文本中搜索指定的字符串,并将该字符串拆分为包含三个元素的元组: * 第一个元素包含指定字符串之前的部分。 * 第二个元素包含指定的字符串。 * 第三个元素包含字符串后面的部分。 ```py txt = "my name is lokesh gupta" x = txt.partition("lokesh") print(x) # ('my name is ', 'lokesh', ' gupta') print(x[0]) # my name is print(x[1]) # lokesh print(x[2]) # gupta ``` #### 6.29 `replace()` 它将指定的短语替换为另一个指定的短语。 它有两种形式: * `string.replace(oldvalue, newvalue)` * `string.replace(oldvalue, newvalue, count)` – `count`指定要替换的匹配次数。 默认为所有事件。 ```py txt = "A A A A A" x = txt.replace("A", "B") print(x) # B B B B B x = txt.replace("A", "B", 2) print(x) # B B A A A ``` #### 6.30 `rfind()` 它查找指定值的最后一次出现。 如果在给定的文本中找不到该值,则返回`-1`。 ```py txt = "my name is lokesh gupta" x = txt.rfind("lokesh") print(x) # 11 x = txt.rfind("amit") print(x) # -1 ``` #### 6.31 `rindex()` 它查找指定值的最后一次出现,如果找不到该值,则会引发异常。 ```py txt = "my name is lokesh gupta" x = txt.rindex("lokesh") print(x) # 11 x = txt.rindex("amit") # ValueError: substring not found ``` #### 6.32 `rjust()` 它将使用指定的字符(默认为空格)作为填充字符来右对齐字符串。 ```py txt = "lokesh" x = txt.rjust(20,"#") print(x, "is my name") # ##############lokesh is my name ``` #### 6.33 `rpartition()` 它搜索指定字符串的最后一次出现,并将该字符串拆分为包含三个元素的元组。 * 第一个元素包含指定字符串之前的部分。 * 第二个元素包含指定的字符串。 * 第三个元素包含字符串后面的部分。 ```py txt = "my name is lokesh gupta" x = txt.rpartition("lokesh") print(x) # ('my name is ', 'lokesh', ' gupta') print(x[0]) # my name is print(x[1]) # lokesh print(x[2]) # gupta ``` #### 6.34 `rsplit()` 它将字符串从右开始拆分为列表。 ```py txt = "apple, banana, cherry" x = txt.rsplit(", ") print(x) # ['apple', 'banana', 'cherry'] ``` #### 6.35 `rstrip()` 它删除所有结尾字符(字符串末尾的字符),空格是默认的结尾字符。 ```py txt = " lokesh " x = txt.rstrip() print(x) # ' lokesh' ``` #### 6.36 [`split()`](https://howtodoinjava.com/python/split-string/) 它将字符串拆分为列表。 您可以指定分隔符。 默认分隔符为空格。 ```py txt = "my name is lokesh" x = txt.split() print(x) # ['my', 'name', 'is', 'lokesh'] ``` #### 6.37 `splitlines()` 通过在换行符处进行拆分,它将字符串拆分为列表。 ```py txt = "my name\nis lokesh" x = txt.splitlines() print(x) # ['my name', 'is lokesh'] ``` #### 6.38 [`startswith()`](https://howtodoinjava.com/python/string-startswith/) 如果字符串以指定值开头,则返回`True`,否则返回`False`。 字符串比较区分大小写。 ```py txt = "my name is lokesh" print( txt.startswith("my") ) # True print( txt.startswith("My") ) # False ``` #### 6.39 `strip()` 它将删除所有前导(开头的空格)和结尾(结尾的空格)字符(默认为空格)。 ```py txt = " my name is lokesh " print( txt.strip() ) # 'my name is lokesh' ``` #### 6.40 `swapcase()` 它返回一个字符串,其中所有大写字母均为小写字母,反之亦然。 ```py txt = "My Name Is Lokesh Gupta" print( txt.swapcase() ) # mY nAME iS lOKESH gUPTA ``` #### 6.41 `title()` 它返回一个字符串,其中每个单词的第一个字符均为大写。 如果单词开头包含数字或符号,则其后的第一个字母将转换为大写字母。 ```py print( "lokesh gupta".title() ) # Lokesh Gupta print( "38lokesh gupta".title() ) # 38Lokesh Gupta print( "1\. lokesh gupta".title() ) # Lokesh Gupta ``` #### 6.42 `translate()` 它需要转换表根据映射表替换/转换给定字符串中的字符。 ```py translation = {97: None, 98: None, 99: 105} string = "abcdef" print( string.translate(translation) ) # idef ``` #### 6.43 `upper()` 它返回一个字符串,其中所有字符均大写。 符号和数字将被忽略。 ```py txt = "lokesh gupta" print( txt.upper() ) # LOKESH GUPTA ``` #### 6.44 `zfill()` 它在字符串的开头添加零(0),直到达到指定的长度。 ```py txt = "100" x = txt.zfill(10) print( 0000000100 ) # 0000000100 ``` 学习愉快!