7.2 数据类型之字符串
2020-05-08 08:58
90 查看
7.2 字符串String
Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
Python中的字符串不能改变。
Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
7.2.1 创建格式:
string1 = Value1’’
string2 = “Value2”
7.2.2 常用功能
#!/usr/bin/env python # -*- coding:UTF-8 -*- # Author: Fan Carey hey = "Hello World!!!" author = "f_carey" # 更新 print("hey[:6] + this is new string!-->", hey[:6] + 'this is new string!') # 输出:hey[:6] + this is new string!--> Hello this is new string! ********************* 字符串拼接: python中的字符串在C语言中体现为是一个字符数组,每次创建、修改、+字符串的话,都需要从内存中重新开辟空间。 ********************* # 转义 # 'r/R':所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 # 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 print("r\'\\n\'-->输出结果:" + r'\n') #输出:r'\n'-->输出结果:\n print("R\'\\n\'-->输出结果:" + R'\n') #输出:R'\n'-->输出结果:\n # 格式化字符串 # '%'格式化字符串 print("这是hey程序:%s" % hey) # 输出:这是hey程序:Hello World!!! # f-string:是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。 print(f'{hey}') # 输出:Hello World!!! print("这是hey程序:%s,由%s编写。" % (hey, author)) # 这是hey程序:Hello World!!!,由f_carey编写。 print(f'{1+3}') # 输出:4 x = 1 print(f'{x + 3 = }') # 输出:x + 3 = 4 # format print("my name is {name}, and {age} old".format(name='carey', age=18)) # 输出:my name is carey, and 18 old # format_map print("my name is {name}, and {age} old".format_map({'name': 'carey', 'age': 18})) # 输出:my name is carey, and 18 old # '"""' """便于引用其他类型代码 """ html代码,特殊字符无需转义 """ """
7.2.2.1 字符串运算
# '+' print("hey + author 输出结果:", hey + author) # 输出:hey + author 输出结果: Hello World!!!f_carey # '*' print("hey * 2 输出结果:", hey * 2) # 输出:hey * 2 输出结果: Hello World!!!Hello World!!! # '[]' print("hey[1] 输出结果:", hey[1]) # 输出:hey[1] 输出结果: e # '[:]'遵循左闭右开原则,str[0:6] 是不包含第 7 个字符的。 print("hey[:6] 输出结果:", hey[:6]) # 输出:hey[:6] 输出结果: Hello # 'in' print("He in hey 输出结果:", 'He' in hey) # 输出:He in hey 输出结果: True # 'not in' print("He no in hey 输出结果:", 'He' not in hey) # 输出:He no in hey 输出结果: False
7.2.2.2 字符串截取
格式如下:变量[头下标:尾下标:步长]
索引值以 0 为开始值,-1 为从末尾的开始位置,步长为负数表示逆向读取
hey = "Hello World!!!" author = "f_carey" print("hey[0]:", hey[0]) # 输出:hey[0]: H print("hey[:]", hey[:]) # 输出:hey[:] Hello World!!! print("hey[1:5]", hey[1:5]) # 输出:hey[1:5] ello print("hey[1:]", hey[1:5]) # 输出:hey[1:] ello print(hey[::2]) # 输出:HloWrd! # 逆向读取 print(hey[::-1]) # 输出:!!!dlroW olleH
7.2.2.3 其他功能
para_str = """这是一个多行字符串的实例 多行字符串可以使用制表符 TAB ( \t )。 也可以使用换行符 [ \n ]。 """ # 访问 print(para_str) # 输出:这是一个多行字符串的实例 多行字符串可以使用制表符 TAB ( )。 也可以使用换行符 [ ]。 # 空字符串 string = '' print(string) # 输出:
7.3 字符串的常用方法
字符串由 str类代表,可以使用dir(str)查看该类包含哪些方法 ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] str1 = "Hello World! ß" str2 = "ß Hello World! ß" str3 = "Hello World\t!" str4 = "Hello" # capitalize,首字母大写,若存在其他大写字符,将转为小写; print(str1.capitalize()) # 输出:Hello world! ß print(str2.capitalize()) # 输出:Ss hello world! ß # 大写转小写,德语中'ß'的小写是'ss' print(str1.casefold()) # 输出:hello world! ss # 大写转小写,只对 ASCII 也就是 'A-Z'有效 print(str1.lower()) # 输出:hello world! ß # 大写转小写 print(str1.upper()) # 输出:HELLO WORLD! SS # 将字符串居中,长度为50,缺少的内容由"*"补充 print(str1.center(50, '*')) # 输出:******************Hello World! ß****************** # 计算str1中存在多少个'l'字符 print(str1.count('l')) # 输出:3 # 计算str1中在索引5到索引10中,存在多少个'l'字符,即:" World" print(str1.count('l', 5, 10)) # 输出:1 # 字符编码 print(str1.encode(encoding='UTF-8', errors='strict')) # encoding -- 要使用的编码,如"UTF-8、gb2312"。 # errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误将产生一个UnicodeError。 # 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。 # 输出:b'Hello World! \xc3\x9f' # 查询最后一个字符是否为所要查询的字符 print(str1.endswith('ß')) # 输出:True # 查询第一个字符是否为所要查询的字符 print(str1.startswith('H')) # 输出:True # 把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 5. print(str3.expandtabs()) # 输出:Hello World ! # 查找第一个'l'在字符串中所在索引位置; print(str3.find('l')) # 输出:2 # 查找从右边开始第一个'l'在字符串中所在索引位置; print(str3.rfind('l')) # 输出:9 # index:查找第一个'l'在字符串中所在索引位置; print(str3.index('l')) # 输出:2 # index:查找从右边开始第一个'l'在字符串中所在索引位置; print(str3.rindex('l')) # 输出:9 # isalnum: 确认是否字符串为阿拉伯数字 print(str3.isalnum()) # 输出:False # isalpha:确认是否字符串为阿拉伯字母 print(str4.isalpha()) # 输出:True # isascii:确认是否字符串为ascii码 print(str3.isascii()) # 输出:True # isidentifier:确认字符串是否是有效的 Python 标识符,可用来判断变量名是否合法 print(str4.isidentifier()) # 输出:True # islower:确认字符串是否为全部小写 print(str3.islower()) # 输出:False # isspace:确认字符串是否为空格 print(str3.isspace()) # 输出:False # isdecimal:确认字符串是否为十进制字符。这种方法只存在于unicode对象。 print(str3.isdecimal()) # 输出:False # isdigit:确认字符串是否为Unicode数字,byte数字(单字节),全角数字(双字节) print(str3.isdigit()) # 输出:False # isnumeric:确认字符串是否为Unicode数字,全角数字(双字节),罗马数字,汉字数字 print(str3.isnumeric()) # 输出:False # istitle:确认字符串是否为全部为首字母大写 print(str3.istitle()) # 输出:True # isupper:确认字符串是否为全部为大写 print(str3.isupper()) # 输出:False # isprintable:确认字符串是否为可打印,如:/t与/n无法打印 print(str4.isprintable()) # 输出:True # join:连接任意数量的字符串。 print(str4.join(['*', '+', '&'])) # 输出:*Hello+Hello& # ljust:生成50个字符,字符串居左。 print(str4.ljust(50, '*')) # 输出:Hello********************************************* # ljust:生成50个字符,字符串居右。 print(str4.rjust(50, '*')) # 输出:*********************************************Hello # lstrip:移除字符串头指定的字符(默认为空格或换行符)或字符序列。 # 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 print(str2.lstrip('ß')) # 输出: Hello World! ß # rstrip:移除字符串尾指定的字符(默认为空格或换行符)或字符序列。 # 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 print(str2.rstrip('ß')) # 输出:ß Hello World! # strip:移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 # 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 print(str2.strip('ß')) # 输出: Hello World! # maketrans:创建字符映射的转换表 intab = "helo" outab = "1234" trantab = str.maketrans(intab, outab) print(str3.translate(trantab)) # 输出:H2334 W4r3d ! # partition:根据指定的分隔符将字符串进行分割。 # 如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 print(str3.partition('o')) # 输出:('Hell', 'o', ' World\t!') # rpartition:从右边开始根据指定的分隔符将字符串进行分割。 # 如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 print(str3.rpartition('o')) # 输出:('Hello W', 'o', 'rld\t!') # replace:截掉字符串右边的空格或指定字符。 print(str3.replace('l', 'L')) # 输出:HeLLo WorLd ! # split:以‘l’作为分割字符,对字符串进行分割。默认没有限制 print(str3.split('l')) # 输出:['He', '', 'o Wor', 'd\t!'] # rsplit:从右边开始,以‘l’作为分割字符,对字符串进行分割。 print(str3.rsplit('l', 1)) # 输出:['Hello Wor', 'd\t!'] # splitlines:按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表, # keepends:在输出结果里是否保留换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符。 str5 = 'abc \n def \r ghi\r\n' print(str5.splitlines()) print(str5.splitlines(True)) # 输出:['abc ', ' def ', ' ghi'] # ['abc \n', ' def \r', ' ghi\r\n'] # swapcase:大小写互换。 print(str3.swapcase()) # 输出:hELLO wORLD ! # title:所有单词都是以大写开始 str5 = 'my name is carey' print(str5.title()) # 输出:My Name Is Carey # zfill:指定长度的字符串,原字符串右对齐,前面填充0。 print(str3.zfill(50)) # 输出:0000000000000000000000000000000000000Hello World !
相关文章推荐
- Java中字符串对象和基本数据类型包装类
- Python基础数据类型-字符串(string)
- 用enum类型数据解决switch case选择字符串的问题
- python 01数据类型转换_如何将所有或部分dataframe的数据类型转换为字符串
- 【PHP基础 02-常量及数据类型】PHP的字符串的定义方式及各自区别?
- Go语言中其他数据与字符串类型的转换
- MySQL数据类型--------字符串类型实战
- 数据类型与字符串
- Python学习笔记(一)--Python基础知识:变量、数据类型、模块与字符串
- 字符串处理,数据类型
- python数据类型之字符串
- jQuery使用serialize(),serializeArray()方法取得表单数据+字符串和对象类型两种表单提交的方法
- Python数据类型(一)字符串
- Java学习总结--字符串String类和基本的数据类型有什么区别
- js判断数据类型如判断是否为数组是否为字符串等等
- Python核心数据类型——字符串(2)
- 字符串与基本数据类型的转换
- 字符串String数据类型的探讨
- 字符串String数据类型的探讨
- 【JAVA学习】java基本数据类型与字符串之间的转换(基本数据类型、对象封装类、自动装箱、自动拆箱)