Lesson 2-3(字符串)
2.5 字符串
--- 字符串是不可变的。
>>> str = "Hello world!"
>>> str[-6:-1] = "python"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
2.5.1 字符串格式设置
--- 使用字符串方法format,字段名({}部分)可以留空自动编号,或者使用索引手动编号,或者使用变量。(还可以通过:号后面添加格式说明符)
>>> "H{}llo worl{}!".format('e', 'd')
'Hello world!'
>>> "H{0}llo worl{1}!".format('e', 'd')
'Hello world!'
>>> "H{1}llo worl{0}!".format('d', 'e')
'Hello world!'
>>> "H{a}llo worl{b}!".format(b = 'd', a = 'e')
'Hello world!'
>>> "H{a}llo worl{b:.3f}!".format(b = 1.2345, a = 'e')
'Hello worl1.234!'
>>>
--- 使用字符串方法format,字段名可以自动编号和变量一起使用,也可以手动编号和变量一起使用,但不能自动编号和手动编号一起使用。
>>> "H{1}l{a}o wo{b}l{0}!".format('d', 'e', a = 'l', b = 'r')
'Hello world!'
>>> "H{}l{a}o wo{b}l{}!".format('e', 'd', a = 'l', b = 'r')
'Hello world!'
>>> "H{}l{2}o wo{3}l{}!".format('e', 'd', 'l', 'r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field specification
>>>
--- 使用字符串方法format,当变量名称与替换字段同名时,可使用f字符串(在字符串前面加 f )
>>> from math import e
>>> "E = {e}".format(e = e)
'E = 2.718281828459045'
>>> from math import e
>>> f"E = {e}"
'E = 2.718281828459045'
>>>
2.5.2 基本转换
--- 转换标志:在感叹号❗后面的单字符,常见的有s、r、a分别使用str、repr、ASCII进行转换。
>>> "{pi!s},{pi!r},{pi!a}".format(pi = 'π')
"π,'π','\\u03c0'"
>>>
--- 还可以指定要转换的值是哪种类型。
>>> "The number is {num}".format(num = 42)
'The number is 42'
>>> "The number is {num:f}".format(num = 42)
'The number is 42.000000'
>>> "The number is {num:b}".format(num = 42)
'The number is 101010'
>>>
2.5.3 宽度、精度和千位分隔符
>>> "The number is {num:10}".format(num = 42)
'The number is 42'
>>> "The number is {num:10}".format(num = "Hello")
'The number is Hello '
>>> "The number is {num:10.5f}".format(num = 3.1415926)
'The number is 3.14159'
>>> "The number is {num:,}".format(num = 3.14**15)
'The number is 28,440,990.75034137'
>>>
2.6 字符串方法
2.6.1 位置对齐
--- 方法center,通过在两边填充字符(默认为空格),让字符串居中。(第一个参数指新字符串的长度,第二参数为填充字符)
>>> "Hello world!".center(30)
' Hello world! '
>>> "Hello world!".center(30,"*")
'*********Hello world!*********'
>>>
--- 方法rjust,通过在左边填充字符(默认为空格),让字符串居右。
>>> "Hello world!".rjust(30)
' Hello world!'
>>> "Hello world!".rjust(30,"*")
'******************Hello world!'
>>>
--- 方法ljust,通过在右边填充字符(默认为空格),让字符串居左。
>>> "Hello world!".ljust(30)
'Hello world! '
>>> "Hello world!".ljust(30,"*")
'Hello world!******************'
>>>
2.6.2 查找和替换
--- 方法find,在字符串中查找子串,如果找到,则返回第一个找到位置的索引,如果没找到则返回 -1 。
&、 可以指定搜索的起点和终点,终点如果省略,则指搜索到末尾。起点值和终点值遵循左闭右开原则。
&、注意跟成员资格in和not in 的区别,成员资格返回的是布尔值,方法find返回的是索引值或 -1 。
>>> "Hello world!".find("o")
4
>>> "Hello world!".find("lo")
3
>>> "Hello world!".find("ol")
-1
>>> "Hello world!".find("lo", 1, 10)
3
>>> "Hello world!".find("!", 1, )
11
>>> "lo" in "Hello world!"
True
>>> "ol" in "Hello world!"
False
>>>
--- 方法replace,将指定子串替换为另一个字符串,并返回替换后的结果。
&、如果没有找到指定的子串,则返回原字符串。
&、用于替换的字符串可以和指定的子串不等长。
>>> "Hello world!".replace("lo", "@@")
'Hel@@ world!'
>>> "Hello world!".replace("ol", "@@")
'Hello world!'
>>> "Hello world!".replace("world", "python")
'Hello python!'
>>>
--- 方法translate,和方法replace一样替换字符串的指定部分,不同的是它只能进行单字符替换。
&、使用方法translate前,必须对字符串类型str调用方法maketrans创建一个转换表。
&、方法maketrans通常接受两个参数,两个长度相等的字符串,指定将第一个字符串中的每个字符对应替换为第二个字符串的字符。
&、方法maketrans还可以指定第三个参数,指定将要删除的字符串。
>>> tab = str.maketrans("l", "@")
>>> "Hello world!".translate(tab)
'He@@o wor@d!'
>>> tab = str.maketrans("lo", "@^")
>>> "Hello world!".translate(tab)
'He@@^ w^r@d!'
>>> tab = str.maketrans("l", "@", " ")
>>> "Hello world!".translate(tab)
'He@@owor@d!'
>>> tab = str.maketrans("l", "@", "od")
>>> "Hello world!".translate(tab)
'He@@ wr@!'
>>>
2.6.3 大小写
--- 方法lower,返回全小写的新字符串。
>>> "Hello world!".lower()
'hello world!'
>>> "hello world!".lower()
'hello world!'
>>>
--- 方法upper,返回全大写的新字符串。
>>> "Hello world!".upper()
'HELLO WORLD!'
>>>
2.6.4 连接和拆分
--- 方法join,通过指定的字符串连接合并序列中的元素,序列中的元素必须都是字符串。
&、注意和别的字符串方法调用方式的区别,对指定字符串调用方法join,并且传入一个序列值。
>>> "-".join("Hello world!")
'H-e-l-l-o- -w-o-r-l-d-!'
>>> "-".join(['', '', ''])
'1-2-3'
>>> "-".join([1, 2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>>
--- 方法split,作用与方法join相反,将字符串拆分为序列。
&、如果没有指定分隔符,将默认在单个或多个连续的空白字符处进行拆分。
>>> "Hello world!".split("l")
['He', '', 'o wor', 'd!']
>>> "1+2+3".split("+")
['', '', '']
>>> "Hello my python!".split()
['Hello', 'my', 'python!']
>>>
2.6.5 空格删除
--- 方法strip,将字符串开头和末尾的空白格删除(不删除中间的空白格),并返回删除后的结果。
&、方法strip,可选带一个参数,表示字符串开头和末尾包含该参数指定的字符都删除,直到不是为止。(参数中各个字符顺序不重要,效果一样。)
>>> " Hello world! ".strip()
'Hello world!'
>>> " Hello world!".strip()
'Hello world!'
>>> "Hello world! ".strip()
'Hello world!'
>>> "Hello world!".strip("eH!l")
'o world'
>>> "Hello world!".strip("leH!")
'o world'
>>>
--- 方法lstrip,删除左边空白字符,也可选带入一个参数。
>>> " Hello world! ".lstrip()
'Hello world! '
>>> " Hello world! ".lstrip("Hle ")
'o world! '
>>>
--- 方法rstrip,删除右边空白字符,也可选带入一个参数。
>>> " Hello world! ".rstrip()
' Hello world!'
>>> " Hello world! ".rstrip(" l!d")
' Hello wor'
>>>
2.6.6 判断类方法(常用于登录认证)
--- 方法islower,判断原字符串至少有一个字母,如果所有字母都是小写,返回布尔值True,否则返回布尔值Flase 。
>>> "hello world!".islower()
True
>>> "Hello world!".islower()
False
>>>
--- 方法isupper,判断原字符串至少有一个字母,如果所有字母都是大写,返回布尔值True,否则返回布尔值Flase 。
>>> "HELLO WORLD!".isupper()
True
>>> "Hello world!".isupper()
False
>>>
&、注意原字符串必须至少有一个字母。
>>> "!@#$%^&*!".isupper()
False
>>> "!@#$%^&*!".islower()
False
>>>
--- 方法isalpha,判断原字符串如果只包含字母,并且非空,则返回布尔值True 。
--- 方法isdecimal,判断原字符串如果只包含数字,并且非空,则返回布尔值True 。
--- 方法isalnum,判断原字符串如果只包含字母和数字,并且非空,则返回布尔值True 。
--- 方法isspace,判断原字符串如果只包含空格、制表符和换行,并且非空,则返回布尔值True 。
--- 方法istitle,判断原字符串如果只包含以大写字母开头,且后面都是小写字母的单词,并且非空,则返回布尔值True 。
--- 方法startswith,判断原字符串如果以指定的字符串开始,原字符串可以为空,则返回布尔值True 。
--- 方法endswith,判断原字符串如果以指定的字符串结束,原字符串可以为空,则返回布尔值True 。
Lesson 2-3(字符串)的更多相关文章
- 如何计算一个字符串表示的计算式的值?——C_递归算法实现
在<C程序设计伴侣>的8.7.3 向main()函数传递数据这一小节中,我们介绍了如何通过main()函数的参数,向程序传递两个数据并计算其和值的简单加法计算器add.exe.这个程序,好 ...
- Python新手学习基础之数据类型——字符串的切片截取
切片截取是python中字符串常见的一些操作,我们会在这篇文章里详细介绍,切片截取的作用是获取子字符或子字符串. 实际上,我们要做的就是使用索引,用冒号分隔两个索引,形式为:变量[头下标:尾下标],冒 ...
- NSString/NSMutable字符串——韩俊强…
1.OC基本数据类型(简单铺垫) // NSInteger 在64 位下相当于long,在非64位下相当于 int: // CGFloat 在64位下相当于double 在非64位下相当 ...
- Python:Day06 元组、字典、字符串
tuple(元组) 元组被称为只读列表,即数据可以被查询,但不能被修改,所以列表的切片操作同样适用于元组. 元组写在( )里,元素之间用逗号隔开. tul1 = ( ) #空元组 tul2 = (20 ...
- day 6 元组、字典、字符串
本节内容 : 1,元组 2,字典 3,字符串作业 produce = [('mac', 9000), ('bicycle', 800), ('computer', 8000), ('book', 50 ...
- GO语言的进阶之路-Golang字符串处理以及文件操作
GO语言的进阶之路-Golang字符串处理以及文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们都知道Golang是一门强类型的语言,相比Python在处理一些并发问题也 ...
- 执行字符串或注释代码段的方法(eval、exec、execfile)
eval:计算字符串中的表达式exec:执行字符串中的语句execfile:用来执行一个文件 需注意的是,exec是一个语句,而eval()和execfile()则是内建built-in函数. 1 2 ...
- python学习 day3 (3月4日)---字符串
字符串: 下标(索引) 切片[起始:终止] 步长[起始:终止:1] 或者-1 从后往前 -1 -2 -3 15个专属方法: 1-6 : 格式:大小写 , 居中(6) s.capitalize() s ...
- python中如何将字符串连接在一起,多倍的字符串如何输出
说明: 在python中,如果有多个字符串,想要连接在一起,或者说想要拼接在一起该如何操作,在此记录下. 操作过程: 1.通过 + 这个加号操作符,将字符串拼接在一起 >>> &qu ...
随机推荐
- Leetcode 5
HashTable Easy 1. 136. Single Number 0与0异或是0,1与1异或也是0,那么我们会得到0 class Solution { public: int singleNu ...
- vim主题颜色
1.VIM主题 查看Vim示例当前的颜色主题 打开一个Vim窗口,输入命令:color或:colorscheme后回车查看当前的颜色主题. Vim实例中设置颜色主题 输入命令"colorsc ...
- did not finish being created even after we waited 189 seconds or 61 attempts. And its status is downloading
did not finish being created even after we waited 189 seconds or 61 attempts. And its status is down ...
- [模板]fhqTreap
用途 平衡树(可实现区间翻转) 原理 和treap一样,中序遍历表示权值的顺序,并且每个点有一个随机的附加值,形成一个堆来保证复杂度 但是不旋转,所有操作通过split和merge实现 分为两种spl ...
- C#面向对象基本概念总结
快过年了,发一篇自己的复习总结.以下内容均是个人理解,如文章有幸被浏览,如有错误的地方欢迎大家提出,相互学习相互进步! 面向对象三大基本特征:封装,继承,多态 一.类 (对象声明的三种方式:以普通基类 ...
- 20175221 MyCP(课下作业,必做)
MyCP(课下作业,必做) 任务详情 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: - java MyCP -tx XXX1.txt XXX2 ...
- (二分查找 拓展) leetcode 162. Find Peak Element && lintcode 75. Find Peak Element
A peak element is an element that is greater than its neighbors. Given an input array nums, where nu ...
- Apache的安装与配置
apahe官网 http://www.apache.org/ 安装及配置https://blog.csdn.net/liyang4534/article/details/78036591 常见问题的处 ...
- cucumber测试项目报错
[INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building th ...
- 001 Unity学习大纲