码迷,mamicode.com
首页 > 编程语言 > 详细

python常用的六个字符串处理方法

时间:2019-06-04 22:51:55      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:strip   大写   str1   seq   run   class   检索   ***   位置   

1.upper(将小写字母转换为大写)

语法:

       str.upper()

参数:

        NA

实例:

a = abc
b = a.upper()
print(b)

结果:

        ABC

 

 

2.lower(将小写字母转换为大写)

语法:

        str.lower

参数:

       NA

实例:

a = HELLO
b = a.lower()
print(b)

结果:

        hello

 

 

3.join(将序列中的元素以指定的字符连接生成一个新的字符串)

语法:

        str.join(sequence)

参数:

        sequence -- 要连接的元素序列。

实例:

a = (‘q‘,‘w‘,‘e‘)
b = ‘_‘
c = b.join(a)
print(c)

结果:q_w_e

 

 

4.split(通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num+1 个子字符串)

语法:

   str.split(str="", num=string.count(str))

参数:

         str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

         num -- 分割次数。默认为 -1, 即分隔所有。

实例:

a = a b c d
print(a.split(" "))
print(a.split(" ",1))

 

结果:

         [‘a‘, ‘b‘, ‘c‘, ‘d‘]

         [‘a‘, ‘b c d‘]

 

 

5.find(检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1)

语法:

   str.find(str, beg=0, end=len(string))

参数:

         str -- 指定检索的字符串

         beg -- 开始索引,默认为0。

         end -- 结束索引,默认为字符串的长度。

实例:

str1 = "Runoob example....wow!!!"
str2 = "exam";
 
print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))

 

结果:

         7

         7

        -1

 

 

 

6.strip(移除字符串头尾指定的字符(默认为空格)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。)

语法:

    str.strip([chars])

参数:

          chars -- 移除字符串头尾指定的字符序列

实例:

str = "*****this is **string** example....wow!!!*****"
print (str.strip( * )) 

 

结果:

        this is **string** example....wow!!!

 

python常用的六个字符串处理方法

标签:strip   大写   str1   seq   run   class   检索   ***   位置   

原文地址:https://www.cnblogs.com/zhangzhongming/p/10976124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!