字符串详解

字符串的用法是最多的,很多功能的实现都离不开字符串,而且字符串的使用方法也很多,这里面不能说全部给大家一一介绍,只能说把一些常用的列举出来,方便回忆或者说供大家参考,谢谢!请继续往下看~~~

先看下字符串的内置方法有哪些?

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

看完上面,字符串的内置方法还是蛮多的。那么我们看看他们是如何使用的。

字符串定义:
*1.引号包围,不可变(指的是不可以对字符串进行修改)得序列(凡是能够通过索引取值的都是序列)。
*2.不可变对象(字符串)在调用自身方法时,不会改变原有内容。

字符串创建:

     ' '
" "
""" 或者 '''

1.单引号和双引号,字符串可以嵌套使用,不可以交叉使用。
2.三引号经常用于多行注释

>>> print '''hello,jim my name is bob!
... how are you?
... welcome to china!
... byebye
... '''

输出结果:

hello,jim my name is bob!
how are you?
welcome to china!
byebye

3.字符串中的\转义字符

>>> 'let\'s go jim we are go to school!'
"let's go jim we are go to school!"

字符串中的\n

>>> print '''hello,zhaoming\nhow are you?'''
hello,zhaoming
how are you?

4.字符串之 原始字符串 r

>>> print r'C:\now\abc\bcd\efg\aaa\nnn\bmb'
C:\now\abc\bcd\efg\aaa\nnn\bmb
>>> 'C:\now'
'C:\now'
>>> print 'C:\now'
C:
ow
>>> print 'C:\\now'
C:\now

5.字符串拼接 (通过加号+拼接)

>>> name = "zhangshan"
>>> age = '25'
>>> name + age
'zhangshan25'
>>> name = "zhangshan"
>>> age = 25
>>> name + str(age)
'zhangshan25'
>>> name + str(age) + 'how are you?'
'zhangshan25how are you?

6.字符串格式化输出
1.通过% 格式化操作 %s替换所有类型 %d替换整型 %f替换浮点型

>>> name = 'lishi'
>>> age = 155
>>> 'hello,%s my age is %s'%(name,age)
'hello,lishi my age is 155'
>>> 'hello,%s my age is %s'%(age,name)
'hello,155 my age is lishi'
>>> 'hello,%d my age is %s'%(name,age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> 'hello,%s my age is %d'%(name,age)
'hello,lishi my age is 155'

7.判断变量类型内置函数

type(a)
isinstance(a,b) a为变量,b为类型 检查是否匹配 匹配为真 不匹配为假
>>> isinstance(111,int)
True
>>> isinstance('',int)
False
>>> isinstance('',str)
True
>>> isinstance(11.00,float)
True

8.字符串复制 *

>>> 'hello' + 'zhanshan' + 'nihao---->'*3
'hellozhanshannihao---->nihao---->nihao---->'

9.字符串判断

>>> 'zhang' in 'zhangshan'
True
>>> '12' in 'zhangshan'
False
>>> 'zhang' not in 'zhangshan'
False

10.字符串索引
索引从0开始,默认取值方向从左到右。单个取值

>>> 'hello_world'
'hello_world'
>>> 'hello_world'[0]
'h'
>>> 'hello_world'[1]
'e'
>>> 'hello_world'[2]
'l'

普通截取 [开始端:结束端] 包含开始端 不包含结尾端

>>> 'hello_world'
>>> demo[0:11]
'hello_world'
>>> demo[:]
'hello_world'
>>> demo[0:4]
'hell'
>>> demo[0:3]
'hel'

步长截取 [开始端:结束端:步长值] 包含开始端 不包含结尾端 步长按照步长值减1隔取

>>> demo = 'hello_world'
>>> demo[::2]
'hlowrd'
>>> demo[::]
'hello_world'
>>> demo[::2]
'hlowrd'
>>> demo[:5:2]
'hlo'
>>> demo[:5:2]
>>> demo[::3]
'hlwl'

反向截取 [开始端:结束端] 包含开始端 不包含结尾端

>>> demo = 'hello_world'
>>> demo[-1]
'd'
>>> demo[-2]
'l'
>>> demo[-3]
'r'
>>> demo[-5:-1]
'worl'
>>> demo[-5:0]
''
>>> demo[-5:]
'world'

特殊情况

>>> demo = 'hello_world'
>>> demo[5:0]
''
>>> demo[5:0]
''
>>> demo[0:12]
'hello_world'
>>> demo[0:13]
'hello_world'
>>> demo = 'hello_world'
>>> demo[-1:-5]
''
>>> demo[-3:-5]
''
>>> demo[-20:]
'hello_world'

11.字符串常用操作函数

dir(str) 查看字符串的用法

1.字符串-find()函数
可以查找字符串中的元素的索引位,如果查询一个不存在的元素返回值为-1,如果能查到指定元素
那么就会返回该元素对应的索引位。

>>> demo = 'hello_world'
>>> demo.find('e')
1
>>> demo.find('m')
-1
>>> demo = 'hello_werld'
>>> demo.find('e')
1
>>> demo.find('w')
6

2.字符串-split()函数(分隔函数)

>>> demo = 'hello_werld'
>>> demo.split('e')
['h', 'llo_w', 'rld']
>>> demo = 'hello_world'
>>> demo.split('e')
['h', 'llo_world']
>>> demo.split('_')
['hello', 'world']
>>> demo.split('')

3.字符串-upper()函数 将字符串中所有的字符变成大写
(不可变对象调用自身方法不会改变自身的原有内容)

>>> demo = 'hello_world'
>>> demo.upper()
'HELLO_WORLD'
>>> demo
'hello_world'
>>> abc=demo.upper()
>>> abc
'HELLO_WORLD'
>>> demo
'hello_world'
>>>

4.字符串-lower()函数 将字符串中所有的字符变成大写

>>> abc='HELLO_WORLD'
>>> abc
'HELLO_WORLD'
>>> abc.lower()
'hello_world'
>>>

5.字符串的替换-replace(a,b) a是要替换的原内容 b是替换的新内容

>>> url='www.baidu.com'
>>> url
'www.baidu.com'
>>> url.replace('baidu','sina')
'www.sina.com'
>>> url
'www.baidu.com'
>>> demo=url.replace('baidu','sina')
>>> demo
'www.sina.com'

6.字符串的- join函数(分隔)

>>> url='www.baidu.com'
>>> ':'.join(url)
'w:w:w:.:b:a:i:d:u:.:c:o:m'
>>> username='zhangshan,lishi,wangwu'
>>> ':'.join(username)
'z:h:a:n:g:s:h:a:n:,:l:i:s:h:i:,:w:a:n:g:w:u'
>>> username='zhangshan,lishi,wangwu'
>>> username.split(',')[0]
'zhangshan'
>>> username.split(',')[1]
'lishi'
>>> username.split(',')[2]
'wangwu'

7.字符串的strip 忽略字符串前后空格

>>> username=' zhangshan,lishi,wangwu '
>>> username
' zhangshan,lishi,wangwu '
>>> username.strip()
'zhangshan,lishi,wangwu'

(转载请标明出处,谢谢!)

最新文章

  1. 3172: [Tjoi2013]单词
  2. 蒙特卡洛马尔科夫链(MCMC)
  3. ml的线性回归应用(python语言)
  4. 转:Tomcat启动过程中找不到JAVA_HOME JRE_HOME的解决方法
  5. 给定一个整数实现奇偶bit位互换
  6. Opencv step by step - 视频变换
  7. Gym 100801A Alex Origami Squares (求正方形边长)
  8. OpenCV_轮廓的查找、表达、绘制、特性及匹配
  9. 应该始终以PreparedStatement代替Statement
  10. 升级ssh编译错误
  11. vijosP1092 全排列
  12. zabbix邮件告警
  13. (转载)MVC 4.0 PartialView()与View()真的一样吗?
  14. Unity uGUI 登录界面
  15. UML之活动图
  16. Spring Boot Web 开发注解篇
  17. C# - 获取windows系统特殊文件夹路径
  18. ImportError: libcudnn.so.5: cannot open shared object file: No such file or directory
  19. centos7.3安装nvidia驱动和cuda9
  20. 20145101《Java程序设计》第5周学习总结

热门文章

  1. gradle 安装试用
  2. yield关键字用法与解析(C# 参考)
  3. Des加解密(Java端和Js端配套)解析
  4. 为什么 FastAdmin 的插件不全部免费?
  5. Linux Shell 1&gt;/dev/null 2&gt;&amp;1 含义
  6. module_param 用于动态开启/关闭 驱动打印信息
  7. 安装android studio时候弹出unable to access android sdk add-on list解决方法
  8. AngularJS:Service
  9. EasyUI TreeJson
  10. 在rac集群上开启OEM