Python基础(三):字符串和元组常用方法

字符串

在python中单引号和双引号所表示的字符串并没有区别,字符串具有不可变性,及所有操作均不改变原字符串的值。另外三个双引号和单引号包起来的字符串可以换行写入。

In [83]: '''sss
    ...: ''
    ...: ss'''
Out[83]: "sss\n''\nss"

In [84]: """eee
    ...: eee'"'
    ...: """
Out[84]: 'eee\neee\'"\'\n'

 

查找

find(object,[start,[stop]])方法,其中参数start和stop为可选参数,代表查找范围。find()方法在找不到结果会返回-1,而不会报错,这也是非常重要的一点。

In [78]: str1='hello python'

In [79]: str1.find('p')
Out[79]: 6

In [80]: str1.find('z')
Out[80]: -1

In [81]: str1.find('l',0,2)
Out[81]: -1

In [82]: str1.find('l',0,3)
Out[82]: 2

index()方法和count()方法与列表使用方法一样。具体方法可参照上一节https://www.cnblogs.com/austinjoe/p/9365331.html

修改

split(seq=None,maxsplit=-1)方法可以分割字符串,若方法里不加参数默认按空格分割。maxsplit参数可以选择分割次数,默认是全部分割。

In [85]: str1='hello python hello word!'

In [86]: str1.split()
Out[86]: ['hello', 'python', 'hello', 'word!']

In [87]: str1.split('o')
Out[87]: ['hell', ' pyth', 'n hell', ' w', 'rd!']

In [88]: str1.split('o',2)
Out[88]: ['hell', ' pyth', 'n hello word!']

替换

replace()方法可以替换字符串中的值为令外一个,还可限制替换次数。

In [91]: str1='hello python hello word!'

In [92]: str1.replace('hello','你好')
Out[92]: '你好 python 你好 word!'

In [93]: str1.replace('hello','你好',1)
Out[93]: '你好 python hello word!'

In [94]: str1            #str1值并未改变,字符串的不可变性
Out[94]: 'hello python hello word!'

拼接

字符串的拼接是非常有趣的,方法也是很多的,我主要介绍几种常用的方法。

1.“+”拼接

In [95]: str1='hello'

In [96]: str2='python'

In [97]: str1+str2
Out[97]: 'hellopython'

2.join()方法

这个方法比较重要。列表和元组也可以使用,意义是把该字符串加到可迭代的对象中的每两个元素之间。

In [98]: str1='***'

In [99]: str1.join(['hello','python'])
Out[99]: 'hello***python'

In [101]: str1.join(('a','s','d'))
Out[101]: 'a***s***d'

3.%s占位符

In [102]: str1="%s我是谁?%s" % ('','不知道')

In [103]: str1
Out[103]: '喂我是谁?不知道'

4.format字符串格式化

In [104]: str1="{}你好".format('python')

In [105]: str1
Out[105]: 'python你好'

元组

元组常用的有count()和index()。使用方法与之前所讲的没有差别。

In [107]: tup1=('a','w','e','r','r','w')

In [108]: tup1.count('w')
Out[108]: 2

In [109]: tup1.index('e')
Out[109]: 2

 

posted @ 2018-07-25 14:43  AustinJoe  阅读(174)  评论(0编辑  收藏  举报