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 字符串的更多相关文章

  1. Python高手之路【六】python基础之字符串格式化

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  2. 测试一下StringBuffer和StringBuilder及字面常量拼接三种字符串的效率

    之前一篇里写过字符串常用类的三种方式<java中的字符串相关知识整理>,只不过这个只是分析并不知道他们之间会有多大的区别,或者所谓的StringBuffer能提升多少拼接效率呢?为此写个简 ...

  3. java中的字符串相关知识整理

    字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...

  4. JavaScript 字符串实用常操纪要

    JavaScript 字符串用于存储和处理文本.因此在编写 JS 代码之时她总如影随形,在你处理用户的输入数据的时候,在读取或设置 DOM 对象的属性时,在操作 Cookie 时,在转换各种不同 Da ...

  5. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  6. Redis的简单动态字符串实现

    Redis 没有直接使用 C 语言传统的字符串表示(以空字符结尾的字符数组,以下简称 C 字符串), 而是自己构建了一种名为简单动态字符串(simple dynamic string,sds)的抽象类 ...

  7. ASP.NET加密和解密数据库连接字符串

    大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...

  8. Javascript正则对象方法与字符串正则方法总结

    正则对象 var reg = new Regexp('abc','gi') var reg = /abc/ig 正则方法 test方法(测试某个字符串是否匹配) var str = 'abc123'; ...

  9. 微信小程序中利用时间选择器和js无计算实现定时器(将字符串或秒数转换成倒计时)

    转载注明出处 改成了一个单独的js文件,并修改代码增加了通用性,点击这里查看 今天写小程序,有一个需求就是用户选择时间,然后我这边就要开始倒计时. 因为小程序的限制,所以直接选用时间选择器作为选择定时 ...

  10. ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案

    好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下: 出现乱码的原因: ...

随机推荐

  1. python 中的pipe

    from multiprocessing import Process,Queue,Pipe import os def f(q): # q.send([42,None,'hello']) print ...

  2. 一篇文章详解iOS之AutoResizing、AutoLayout、sizeClass来龙去脉

    前言 iPhone自诞生以来,随着其屏幕尺寸不断的多样化,屏幕适配的技术一直在发展更新.目前,iOS系统版本已经更新到9.3,XCode的最新版本已经是7.3,仅iPhone历史产品的尺寸就已经有4种 ...

  3. webpack中Entry与Output的基础配置

    entry顾名思义,就是打包的入口文件 module.exports = { // 这个文件要做打包,从哪一个文件开始打包 entry: './src/index.js', // 打包文件要放到哪里去 ...

  4. 【CSS-flex】圣杯布局(Holy Grail Layout)、输入框的布局、悬挂式布局、固定的底栏

    1.圣杯布局(Holy Grail Layout) 其指的是一种最常见的网站布局.页面从上到下,分成三个部分:头部(header),躯干(body),尾部(footer).其中躯干又水平分成三栏,从左 ...

  5. Kali-linux渗透攻击应用

    前面依次介绍了Armitage.MSFCONSOLE和MSFCLI接口的概念及使用.本节将介绍使用MSFCONSOLE工具渗透攻击MySQL数据库服务.PostgreSQL数据库服务.Tomcat服务 ...

  6. Notepad++格式化JSON字符串

    窗口 -> 插件 -> Plugin Manager -> Show Plugin Manager,在弹出层中找到"JSON Viewer"选项,将踏勾选上,然后 ...

  7. 解析oracle对select加锁的方法以及锁的查询 转

    转自 https://www.jb51.net/article/37587.htm 本篇文章是对oracle对select加锁的方法以及锁的查询进行了详细的分析介绍,需要的朋友参考下 解析oracle ...

  8. java 进销存 库存管理 销售报表 商户管理 springmvc SSM crm 项目

    系统介绍: 1.系统采用主流的 SSM 框架 jsp JSTL bootstrap html5 (PC浏览器使用) 2.springmvc +spring4.3.7+ mybaits3.3  SSM ...

  9. oracle基础知识过一遍(原创)

    用户.角色.权限.表空间 create tablespace test1_tablespace datafile ‘test1file.dbf’ size 10m; create temporary  ...

  10. Java并发编程(七)终结线程

    线程的状态 一个线程会有如下五个状态 1.新建:线程在被创建时会暂时处于这种状态,此时系统为线程分配资源并对其进行初始化 2.就绪:此时线程已经可以运行,只是系统没有为其分配CPU时间. 3.运行:系 ...