python的字符串处理与特殊函数

本文主要记录了python的字符串处理与其特殊的函数。运行环境:macOS 10.12.6


字符串处理

创建字符串

用引号括起来的字符集合称为字符串,引号可以是一对单引号、双引号、三引号(单/双)。例如:

1
2
3
4
5
6
7
var1 = 'Hello World'
var2 = "Hello World"
var3 = """Hello World"""
var4 = '''Hello World'''
var5 = 'hello "dear"' # hello "dear",此时不需要转义
var6 = "hello 'dear'" # hello 'dear',此时不需要转义
var7 = '''"hello 'dear'"''' # "hello 'dear'",此时不需要转义

注意:

  • 与C不同,python中没有字符类型!
  • 三引号可以将复杂的字符串进行复制:即三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他的特殊字符。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    var1 = """hello
    world
    123456"""
    print var1

    #结果:
    hello
    world
    123456

访问字符串中的值

1
2
3
4
5
6
7
s="hello world madj"
print s[0],s[1],s[-1],s[-2]
print s[0:3]

#结果:
h e j d
hel

字符串的更新

字符串不是在原地址上更新,而是新开辟了一块地址空间,存入新的值。如下示例:

1
2
3
4
5
6
7
8
var1 = "hello world"
print var1,id(var1)
var1 = var1[:6]+'python'
print var1,id(var1)

#结果:
hello world 4400085008
hello python 4400087984

字符串运算符

1
2
3
4
5
6
7
8
9
操作符       描述                        示例
--------------------------------------------------------
+ 字符串连接 a+b 输出结果:HelloPython
* 重复输出字符串 a*2 输出结果:HelloHello
[] 通过索引获取字符串 a[1] 输出结果:e
[:] 截取字符串中的一部分 a[1:4]输出结果:ell
in 成员运算符 如果字符串中包含给定的字符,返回true
not in 成员运算符 如果字符串中不包含给定的字符,返回true
r/R 原始字符串 字符串直接按照字面意思来使用,没有转义或不能打印的字符
1
print r'hello\n'*3      输出结果:hello\nhello\nhello\n

字符串格式化

字符串格式化使用与C中的语法一致。

1
2
3
4
print "My name is %s and weight is %d kg!" % ("madj",50)
^ ^ ^
字符串占位 整型占位 连接符
#结果:My name is madj and weight is 50 kg!


字符串的方法

find() 查询子串位置

1
2
3
find(  str   ,   start (选填)   ,   end (选填)   )     
参数:str为字符串,start为起始位置,end为结束位置
返回:找到的起始索引值,找不到返回-1

示例:

1
2
3
4
5
6
7
mystr = "hello world i am jerry jerry!!"
print mystr.find('jerry') #找到第一次出现的位置
print mystr.find('jerry',18) #从18位置开始找

#结果:
17
23

rfind() 从右边开始查询

1
2
3
rfind(  str   ,   start (选填)   ,   end (选填)   )     
参数:str为字符串,start为起始位置,end为结束位置,从右侧开始往左侧查找
返回:找到的起始索引值,找不到返回-1

index() 查询子串位置

1
2
3
index(  str   ,   start (选填)   ,   end (选填)   )  
参数:str为字符串,start为起始位置,end为结束位置
返回:找到的起始索引值,找不到报异常

rindex() 查询子串位置

1
2
3
rindex(  str   ,   start (选填)   ,   end (选填)   )  
参数:str为字符串,start为起始位置,end为结束位置,从右侧开始查找
返回:找到的起始索引值,找不到报异常

count() 统计子串出现的次数

1
2
3
count(  str   ,   start (选填)   ,   end (选填)   )  
参数:str为字符串,start为起始位置,end为结束位置
返回:子串出现的次数

decode() 按指定格式解码

1
2
3
4
decode(  encoding , errors(选填)   )
参数:encoding 为要使用的编码,如"UTF-8"
errors 默认为 'strict',即如果粗粗哦报ValueError异常,除非error指定的是'ignore'或者'replace'
返回:解码后的值
1
2
3
4
5
6
mystr = "hello world i am jerry jerry!!"
s2 = mystr.decode('UTF-8');
print s2,type(s2)

#结果:
hello world i am jerry jerry!! <type 'unicode'>

replace() 替换

1
2
3
replace(     old    ,    new     ,    count(选填)    )
参数:old替换成new,次数不超过count次
返回:一个新的字符串(注意:原字符串没有改变)
1
2
3
4
5
6
7
8
mystr = "hello world i am jerry jerry!!"
s2 = mystr.replace('jerry','madj',1);
print s2
print mystr

#结果
hello world i am madj jerry!!
hello world i am jerry jerry!!

split() 切片

1
2
3
split(  str ,   count(选填)  )
参数:str 为分隔符,count为分隔的次数
返回:分隔后的一个列表
1
2
3
4
5
6
7
8
9
mystr = "hello world i am jerry jerry!!"
s2 = mystr.split(' ');
s3 = mystr.split(' ',3);
print s2
print s3

#结果:
['hello', 'world', 'i', 'am', 'jerry', 'jerry!!']
['hello', 'world', 'i', 'am jerry jerry!!']

capitalize() 第一个字符大写

1
2
3
capitalize(  )
参数:无
返回:第一个字符大写的字符串
1
2
3
4
5
6
7
mystr = "hello world i am jerry jerry!!"
print mystr.capitalize()
print mystr

#结果:
Hello world i am jerry jerry!!
hello world i am jerry jerry!!

center() 字符串居中

1
2
3
center(  width  )
参数:需要的字符串的宽度
返回:一个元字符串居中,并使用空格填充长度至width的新字符串
1
2
mystr = "hello world i am jerry jerry!!"
print mystr.center(1000)

endswith() 判断结尾

1
2
3
endswith(str)
参数:str为字符串
返回:是则为true,否则为false

startwith() 判断开头

1
2
3
startwith(str)
参数:str为字符串
返回:是则为true,否则为false
1
2
3
4
5
6
7
mystr = "hello world i am jerry jerry!!"
print mystr.endswith('jerry!!')
print mystr.startswith('hello')

#结果:
True
True

expandtabs() 制表符转空格

1
2
3
expandtabs(tabsize)
参数:一个tab转化为几个空格
返回:新字符串
1
2
3
4
5
6
7
mystr = "hello world i am jerry jerry\t!!"
print mystr
print mystr.expandtabs(2)

#结果:
hello world i am jerry jerry !!
hello world i am jerry jerry !!

isalnum() 判断内容

1
如果str至少有一个字符并且所有字符都是字母或者数字,则返回true,否则返回false
1
2
3
4
5
6
7
8
mystr = "hello world i am jerry jerry!!"
mystr2 = "hello"
print mystr.isalnum()
print mystr2.isalnum()

#结果:
False
True

isalpha() 判断内容

1
如果str至少有一个字符并且所有字符都是字母(不包含数字和空格),则返回true,否则返回false

isdigit() 判断内容

1
如果str只包含数字,则返回true,否则返回false

isdecimal() 判断内容

1
如果str只包含十进制数字,则返回true

islower() 判断内容

1
如果str至少包含一个区分大小写的字符,并且他们都是小写,那么返回true

isupper() 判断内容

1
如果str至少包含一个区分大小写的字符,并且他们都是大写,那么返回true

isspace() 判断内容

1
如果str只包含空格,则返回true

join() 每个字符后面插入str,构造出一个新的字符串

1
2
3
join(str)
参数:被插入的字符
返回:新的字符串
1
2
3
4
5
str="hello"
print str.join('***')

#结果:
*hello*hello*

ljust() 左对齐

1
2
3
ljust(width)
参数:新的字符串长度
返回:左对齐后的新字符串,填充空格

rjust() 右对齐

1
2
3
rjust(width)
参数:新的字符串长度
返回:右对齐后的新字符串,填充空格

lstrip() 删除字符串开头的空格(左边)

1
删除字符串开头的空格

rstrip() 删除字符串结尾的空格(右边)

1
删除字符串结尾的空格

partition() 以参数作为分隔,分隔成三个部分

1
partition(str) 将字符串以str分割成三部分,str前,str和str后
1
2
3
4
str="  hello  world jerry!! hahahha"
print str.partition('world')

#结果: (' hello ', 'world', ' jerry!! hahahha')

rpartition() 以参数作为分隔,分隔成三个部分,搜索str时从右侧开始搜索

1
rpartition(str) 将字符串以str分割成三部分,str前,str和str后,搜索str时从右侧开始搜索

splitlines() 按照行分隔

1
按照行分隔,返回一个包含各行作为元素的列表

zfill() 返回长度为width的字符串

1
2
3
zfill(width)
参数:需要的字符串长度
返回:返回长度为width的字符串,原字符串右对齐,前面填充0
1
2
3
4
5
str="hello"
print str.zfill(20)

#结果:
000000000000000hello


函数高级

定义一个函数

1
2
3
4
def functionname( parameters )"
"函数_文档字符串"
functio_suite
return [expression] #也可以没有返回

默认情况下,参数值和参数名称是按函数声明中定义的顺序匹配起来的

按值传递参数和按引用传递参数

  • 按值传递

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #coding=utf-8
    def change(var):
    var=100;
    print "函数中:" , var
    return

    myvar=1
    print "原值:",myvar
    change(myvar)
    print "修改后:",myvar

    #结果:
    原值: 1
    函数中: 100
    修改后: 1

    传递的时候,将值传入,函数内不修改原值。

  • 按引用传递

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #coding=utf-8
    def change(str):
    str.append([1,2,3,4])
    print "函数中:" , str
    return

    mylist=[100,200,300]
    print "原值:",mylist
    change(mylist)
    print "修改后:",mylist

    #结果:
    原值: [100, 200, 300]
    函数中: [100, 200, 300, [1, 2, 3, 4]]
    修改后: [100, 200, 300, [1, 2, 3, 4]]

    传递的时候,将mylist的地址号传入函数。

参数

以下是调用函数时可使用的正式参数类型

  • 必备参数

    • 必备参数必须以正确的顺序传入函数。调用时数量必须和声明时的一样。
      1
      2
      3
      4
      5
      6
      7
      def show(a,b):
      print a
      return

      show('1','2')

      #结果:1
  • 命名参数

    • 调用时将形参名和值一起传入
      1
      2
      3
      4
      5
      6
      7
      def show(a,b):
      print a
      return

      show(b='1',a='2')

      #结果:2
  • 缺省参数

    • 调用函数时,如果缺省参数的值没有传入,则被认为是默认值.
    • 注意:缺省参数必须在最后!!
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      def show(a,b='12345'):
      print a
      print b
      return

      show('1')

      #结果:
      1
      12345
  • 不定长参数

    • 如果需要一个函数能够处理比声明函数时更多的参数,需要使用不定长参数

      1
      2
      3
      4
      def function_suite([formal_args,] *var_args_tuple)
      "函数_文档字符串"
      function_suite
      return [expression]

      加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可以。此时,星号部分是元组类型。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      def show(a,*b):
      print a
      print b
      return

      show('1','2','3')

      #结果:
      1
      ('2', '3')

      因此,可以写为:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      def show(a,*b):
      print a
      for var in b:
      print var
      return

      show('1','2','3')

      #结果:
      1
      2
      3

      此外,还可以将其处理为字典。如下所示:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      def show(a,**b):
      print a
      print b
      return

      show('1',x='2',y='3')

      #结果:
      1
      {'y': '3', 'x': '2'}

      因此,可以写为:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      def show(**b):
      for key in b:
      print key+"===="+b[key]
      return

      show(x='2',y='3')

      #结果:
      y====3
      x====2

匿名函数

用lambda关键词能创建小型匿名函数,这种函数得名于省略了def声明函数的基本步骤。

lambda函数能够接收任何数量的参数,但只能返回一个表达式的值。它与内联函数时不同的。

1
lambda [arg1 [,arg2,...,argn]]:expression

1
2
3
4
5
6
7
sum = lambda arg1,arg2:arg1+arg2;
print sum(10,20)
print type(sum)

#结果:
30
function

return语句

return语句可以返回多个值,这些值变成了元组,然后将该元组的首地址返回,接收的就是该元组了。

1
2
3
4
5
6
def returntest():
return 1,2,3,4,5,6
print returntest()

#结果:
(1, 2, 3, 4, 5, 6)

闭包

内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包

1
2
3
4
5
6
7
8
9
def counter(start=0):
count=[start]
def incr():
count[0] += 1
return count[0]
return incr()
print counter(100)

#结果:101

本文标题:python的字符串处理与特殊函数

文章作者:Jerry

发布时间:2018年02月02日 - 08:45:25

最后更新:2019年09月07日 - 23:43:51

原始链接:https://jerryma0912.github.io/2018/02/02/5-python-string/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。