day 7 字符串
- 6.字符串的常见操作
- 知道方向,不要去背
- 1)find,index #查找
- 2)count 和replace #替换
- 3)split # 分割(数据清洗)
- 4)capitalize 和 title #首字母大写
- 5)startswitch endswitch #开头结尾(上传文件名称盘判断)
- 6)lower,upper #转换为大小写(用户输入同一格式)
- 7)center ,ljust,rjust # 居中显示(网易云歌词)
- 8)strip 去除空格,\n,\t #(数据清洗)
- 9) partition,rpartition #分割 (广播体操带队)
- 10)splitlines # 按行\n分割
- 11) isdigit isalpha isalnum # 注册时,必须是字母和数字的组合
- 12)join #构建字符串
- 13)format: #格式化输出
- 浮点数判断
- type(eval("123")) == int
- type(eval("123.23")) == float
1.num=10 和 num=“10”的区别
numb=10 内存中占用1个字节
num=“10“ 内存中占用3个字节
注意:c语言中 字符串末尾还有\0结束符
2.类型转换
- In [1]: num = 100
- In [2]: num2 = ""
- In [3]: name = alex
- ######################
- In [5]: int(num2)
- Out[5]: 100
- In [6]: str(num)
- Out[6]: ''
- ######################
- In [7]: len(name)
- Out[7]: 4 #在内存占用4个字节
3.字符串拼接的2种方式
- In [9]: a = "lao"
- In [10]: b = "wang"
- In [11]: c = a+b
- In [12]: c
- Out[12]: 'laowang'
- In [13]:
- ########################
- In [13]: A = 10
- In [14]: B = 2
- In [15]: C = A+B
- In [16]: C
- Out[16]: 12
- 完成结果显示
- In [18]: "===langwang==="
- Out[18]: '===langwang==='
- ####################### 第1种方式
- In [19]: e = "===" + a + b + "==="
- In [20]: e
- Out[20]: '===laowang==='
- ####################### 第2种方式
- In [21]: f = "===%s==="%(a+b)
- In [22]: f
- Out[22]: '===laowang==='
4.字符串的下标
- In [23]: name = "abcdef"
- In [24]: name[0] #0 下标
- Out[24]: 'a' #a 元素
- In [25]: name[5]
- Out[25]: 'f'
- ######################## 越界
- In [26]: name[6]
- ---------------------------------------------------------------------------
- IndexError Traceback (most recent call last)
- <ipython-input-26-b480563304b2> in <module>()
- ----> 1 name[6]
- IndexError: string index out of range
- ################# [-3][-2][-1]
- In [29]: name[len(name)-1]
- Out[29]: 'f'
- In [30]: name[-1]
- Out[30]: 'f'
- In [31]: name[-2]
- Out[31]: 'e'
- In [32]: name[-3]
- Out[32]: 'd'
5.切片
- #### 正向切片
- In [33]: name = "abcdefABCDEF"
- 02345678910
- In [35]: name[2:5] #实质 [2:5)
- Out[35]: 'cde'
- In [36]: name[2:6] #实质[2:6) 就是[2:5]
- Out[36]: 'cdef'
- ###### 反向切片
- In [33]: name = "abcdefABCDEF"
- -5-4-3-2-1
- 012345
- In [37]: name[2:-2] #[2: cdefgABCDEF
- Out[37]: 'cdefABCD' # :-2) abcdefgABCD
- #结果 cdefgABCD
- In [38]: name[2:-1]
- Out[38]: 'cdefABCDE'
- In [39]: name[2:-2]
- Out[39]: 'cdefABCD'
- In [40]: name[2:0]
- Out[40]: ''
- In [41]: name[2:] #注意!正序全部
- Out[41]: 'cdefABCDEF'
2)实质:【起始位置:终止位置:步长】
- In [42]: name[2:-1]
- Out[42]: 'cdefABCDE'
- In [43]: name[2:-1:2]
- Out[43]: 'ceACE'
- In [44]: name[2:-1:1]
- Out[44]: 'cdefABCDE'
- In [45]: name[2:-1] #默认步长为1
- Out[45]: 'cdefABCDE'
3)字符串的逆序(倒序)?
- In [46]: name
- Out[46]: 'abcdefABCDEF'
- ####### 正序
- In [47]: name[0:]
- Out[47]: 'abcdefABCDEF'
- In [48]: name[-1:]
- Out[48]: 'F'
- In [49]: name[-1:0]
- Out[49]: ''
- ########## 倒序 (面试必考)
- In [50]: name[-1:0:-1]
- Out[50]: 'FEDCBAfedcb'
- In [51]: name[-1::-1]
- Out[51]: 'FEDCBAfedcba'
- In [52]: name[::-1]
- Out[52]: 'FEDCBAfedcba'
6.字符串的常见操作
知道方向,不要去背
- In [57]: my_str = "hello world python adn pythonxxxxcpp"
- In [59]: my_str.
- my_str.capitalize my_str.isalnum my_str.join my_str.rsplit
- my_str.casefold my_str.isalpha my_str.ljust my_str.rstrip
- my_str.center my_str.isdecimal my_str.lower my_str.split
- my_str.count my_str.isdigit my_str.lstrip my_str.splitlines
- my_str.encode my_str.isidentifier my_str.maketrans my_str.startswith
- my_str.endswith my_str.islower my_str.partition my_str.strip
- my_str.expandtabs my_str.isnumeric my_str.replace my_str.swapcase
- my_str.find my_str.isprintable my_str.rfind my_str.title
- my_str.format my_str.isspace my_str.rindex my_str.translate
- my_str.format_map my_str.istitle my_str.rjust my_str.upper
- my_str.index my_str.isupper my_str.rpartition my_str.zfill
1)find,index查找
- ########## find
- In [60]: my_str.find("world")
- Out[60]: 6 #w的下标
- In [63]: my_str.find("python") #从左边开始find
- Out[63]: 12
- In [64]: my_str.rfind("python") #从右边开始find
- Out[64]: 23
- In [61]: my_str.find("redhat") #没有find out 返回-1
- Out[61]: -1
- ############# index
- In [67]: my_str.index("python")
- Out[67]: 12
- In [68]: my_str.rindex("python")
- Out[68]: 23
- In [66]: my_str.index("redhat")
- ---------------------------------------------------------------------------
- ValueError Traceback (most recent call last)
- <ipython-input-66-44374e6cd47d> in <module>()
- ----> 1 my_str.index("redhat")
- ValueError: substring not found #没有找出返回异常
2)count 和replace
- my_str = "hello world python adn pythonxxxxcpp"
- ######### count
- In [69]: my_str.count("python")
- Out[69]: 2
- In [70]: my_str.count("world")
- Out[70]: 1
- In [71]: my_str.count("rehdat")
- Out[71]: 0
- ######### replace
- In [72]: my_str.replace("world","WORLD")
- Out[72]: 'hello WORLD python adn pythonxxxxcpp'
- In [75]: my_str.replace("python","redhat",1) #替换第1个
- Out[75]: 'hello world redhat adn pythonxxxxcpp'
- In [88]: my_str
- Out[88]: 'hello world python adn pythonxxxxcpp'
- #数字,字符串,元组 不可变类型
3)split 分割(数据清洗)
- In [81]: my_str.split(" ")
- Out[81]: ['hello', 'world', 'python', 'adn', 'pythonxxxxcpp'] #返回list
4)capitalize 和 title 首字母大写
- In [82]: my_str.capitalize()
- Out[82]: 'Hello world python adn pythonxxxxcpp'
- In [83]:
- In [83]: my_str.title()
- Out[83]: 'Hello World Python Adn Pythonxxxxcpp'
5)startswitch endswitch 开头结尾(上传文件名称盘判断)
- #上传文件名称的判断
- In [93]: file_name
- Out[93]: 'redhat.txt'
- In [94]: file_name.endswith(".txt")
- Out[94]: True
- In [95]: file_name.startswith("redhat")
- Out[95]: True
- # 对文件内容的审查,模块 上传病毒
6)lower,upper 转换为大小写(用户输入同一格式)
- In [97]: if choic == "yes":
- ....: print("exit")
- ....: elif choice == "YES":
- ....: print("exit")
- ....: elif ..
- ####### 统一一种格式
- In [100]: choice = "Yes"
- In [101]: choice.lower()
- Out[101]: 'yes'
- In [102]: choice.upper()
- Out[102]: 'YES'
7)center ,ljust,rjust 居中显示(网易云歌词)
- In [105]: lyric = "想要陪你一起看大海"
- In [106]: lyric.center(50)
- Out[106]: ' 想要陪你一起看大海 '
- In [108]: lyric.ljust(50)
- Out[108]: '想要陪你一起看大海 '
- In [107]: lyric.rjust(50)
- Out[107]: ' 想要陪你一起看大海'
8)strip 去除空格,\n,\t(数据清洗)
- In [110]: lyric
- Out[110]: ' 想要陪你一起看大海 '
- In [111]: lyric.lstrip() #去除左\n,\t
- Out[111]: '想要陪你一起看大海 '
- In [112]: lyric.rstrip() #去除右\n,\t
- Out[112]: ' 想要陪你一起看大海'
- In [113]: lyric.strip()
- Out[113]: '想要陪你一起看大海'
9) partition,rpartition 分割 (广播体操带队)
- In [114]: my_str
- Out[114]: 'hello world python adn pythonxxxxcpp'
- In [115]: my_str.partition("python")
- Out[115]: ('hello world ', 'python', ' adn pythonxxxxcpp')
- In [117]: my_str.rpartition("python")
- Out[117]: ('hello world python adn ', 'python', 'xxxxcpp')
10)splitlines 按行\n分割
- In [118]: my_line = "hello\nworld\nxx\nyy\nzz"
- In [119]: print(my_line)
- hello
- world
- xx
- yy
- zz
- In [120]: my_line.splitlines()
- Out[120]: ['hello', 'world', 'xx', 'yy', 'zz']
11) isdigit isalpha isalnum 注册时,必须是字母和数字的组合
- s为字符串
- s.isalnum() 所有字符都是数字或者字母
- s.isalpha() 所有字符都是字母
- s.isdigit() 所有字符都是数字
- s.islower() 所有字符都是小写
- s.isupper() 所有字符都是大写
- s.istitle() 所有单词都是首字母大写,像标题
- s.isspace() 所有字符都是空白字符、\t、\n、\r
- ###### 数字整数 isdigit
- In [12]: num = input("请输入一个选项:")
- 请输入一个选项:1
- In [13]: if num.isdigit():
- int(num)
- print("是数字:",num)
- ....:
- 是数字: 1
- ###### 字母 isalpha
- In [8]: num = input("请输入一个选项:")
- 请输入一个选项:q
- In [9]: if num.isalpha():
- print("是字母")
- print(num)
- ...:
- 是字母
- q
- ##### 注册页面,必须是数字和字母的组合
- In [16]: num = "1q"
- In [17]: num.isdigit()
- Out[17]: False
- In [18]: num.isalpha()
- Out[18]: False
- In [20]: num.isalnum() #alpha
- Out[20]: True #number
- ####### 数字字母组合
- In [14]: num = input("请输入一个选项:")
- 请输入一个选项:1q
- In [15]: if num.isalnum():
- ....: print("是字母和数字",num)
- ....:
- 是字母和数字 1q
12)join 构建字符串
- In [21]: a = ["aa","bb","cc"]
- In [22]: a
- Out[22]: ['aa', 'bb', 'cc']
- In [23]: b = "="
- In [24]: b.join(a)
- Out[24]: 'aa=bb=cc'
- In [25]: b = " "
- In [26]: b.join(a)
- Out[26]: 'aa bb cc'
13)format:格式化输出
- # 格式化输出1
- >>> s = 'myname is {0}, i am {1}'
- >>>
- >>> s.format('alxe',22)
- 'myname is alxe, i am 22'
- # 格式化输出2
- >>> s = 'myname is {name}, i am {age}'
- >>> s.format('alxe',22)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- KeyError: 'name'
- >>>
- >>> s.format(name='alex',age=22)
- 'myname is alex, i am 22'
7.面试题:给定一个字符串Str, 去除所有的 空格和'\t',返回字符串
- (面试题)给定一个字符串Str, 去除所有的 空格和'\t',返回字符串
- ####### 题目
- In [27]: test_str = "hello world nihao \t heihie \t woshi nide\tpython \n ll\ndu"
- ###### 错误做法
- In [30]: test_str.split(" ")
- Out[30]:
- ['hello',
- 'world',
- 'nihao',
- '\t',
- 'heihie',
- '\t',
- 'woshi',
- 'nide\tpython',
- '\n',
- 'll\ndu']
- In [32]: test_str.splitlines()
- Out[32]: ['hello world nihao \t heihie \t woshi nide\tpython ', ' ll', 'du']
- In [33]: test_str.split("\t")
- Out[33]: ['hello world nihao ', ' heihie ', ' woshi nide', 'python \n ll\ndu']
- In [34]: test_str.split("\n")
- Out[34]: ['hello world nihao \t heihie \t woshi nide\tpython ', ' ll', 'du']
- In [35]: test_str.split("\t\n")
- Out[35]: ['hello world nihao \t heihie \t woshi nide\tpython \n ll\ndu']
- ##### 正确做法
- In [36]: test_str.split()
- Out[36]: ['hello', 'world', 'nihao', 'heihie', 'woshi', 'nide', 'python', 'll', 'du']
- ####### 字符串拼接
- In [37]: result = test_str.split()
- In [39]: " ".join(result)
- Out[39]: 'hello world nihao heihie woshi nide python ll du'
- In [38]: "".join(result)
- Out[38]: 'helloworldnihaoheihiewoshinidepythonlldu'
day 7 字符串的更多相关文章
- Python高手之路【六】python基础之字符串格式化
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- 测试一下StringBuffer和StringBuilder及字面常量拼接三种字符串的效率
之前一篇里写过字符串常用类的三种方式<java中的字符串相关知识整理>,只不过这个只是分析并不知道他们之间会有多大的区别,或者所谓的StringBuffer能提升多少拼接效率呢?为此写个简 ...
- java中的字符串相关知识整理
字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...
- JavaScript 字符串实用常操纪要
JavaScript 字符串用于存储和处理文本.因此在编写 JS 代码之时她总如影随形,在你处理用户的输入数据的时候,在读取或设置 DOM 对象的属性时,在操作 Cookie 时,在转换各种不同 Da ...
- Java 字符串格式化详解
Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...
- Redis的简单动态字符串实现
Redis 没有直接使用 C 语言传统的字符串表示(以空字符结尾的字符数组,以下简称 C 字符串), 而是自己构建了一种名为简单动态字符串(simple dynamic string,sds)的抽象类 ...
- ASP.NET加密和解密数据库连接字符串
大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...
- Javascript正则对象方法与字符串正则方法总结
正则对象 var reg = new Regexp('abc','gi') var reg = /abc/ig 正则方法 test方法(测试某个字符串是否匹配) var str = 'abc123'; ...
- 微信小程序中利用时间选择器和js无计算实现定时器(将字符串或秒数转换成倒计时)
转载注明出处 改成了一个单独的js文件,并修改代码增加了通用性,点击这里查看 今天写小程序,有一个需求就是用户选择时间,然后我这边就要开始倒计时. 因为小程序的限制,所以直接选用时间选择器作为选择定时 ...
- ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案
好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下: 出现乱码的原因: ...
随机推荐
- 四级菜单实现(Python)
menu_dict = { '山东' : { '青岛' : { '四方':{'兴隆路','平安路','杭州路'}, '黄岛':{}, '崂山':{} }, '济南' : { '历城':{}, '槐荫' ...
- 批量修改文件格式到UTF-8
系统环境: Unbuntu14.10 目标: 多个文件夹加下的大量.java文件,需要由ASCII,转为UTF-8编码格式,文件嵌套较深. 解决方案: 执行Console中,目标目录下执行一下命令: ...
- TensorFlow函数(二)tf.get_variable() 和 tf.Variable()
tf.Variable(<initial - value>,name=<optional - name>) 此函数用于定义图变量.生成一个初始值为initial - value ...
- H、CSL 的拼图 【多维点的交换】 (“新智认知”杯上海高校程序设计竞赛暨第十七届上海大学程序设计春季联赛)
题目传送门:https://ac.nowcoder.com/acm/contest/551/H 题目描述 众所周知 CSL 不仅玩魔方很强,打麻将也很强.今天他打魔法麻将的时候,在路上撞到了一个被打乱 ...
- VIM之模式
1.模式介绍: 在真正开始使用VIM之前,你必须先了解VIM的模式,否则在 VIM 面前你可能会手足无措.VIM是有模式 编辑器,这意味着 VIM 有多种不同的工作模式,在不同的工作模式下用户相同的操 ...
- python之九九乘法表
for i in range(1,10): print( ) for j in range(1,i+1): print('%d*%d=%d '%(i,j,i*j),end="") ...
- Monkeyrunner测试小实践
环境搭建完成后,我们通过命令打开模拟器,前提是在Eclipse中创建了一个模拟器 (1)cmd命令:emulator -avd 模拟器名称 启动了模拟器,此时你就会看到一个安卓模拟器的弹出 (2)cm ...
- Shell笔记-04
如果表达式中包含特殊字符,Shell 将会进行替换.例如,在双引号中使用变量就是一种替换,转义字符也是一种替换. 举个例子: #!/bin/bash a=10 echo -e "Value ...
- 基于maven的JavaWeb项目构建部署
需要准备的安装文件: 1 JDk http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html jdk-8 ...
- Linux环境下部署SpringBoot项目
1.在pom文件中添加maven插件 <build> <plugins> <plugin> <groupid>org.springframework.b ...