**

Python中字符串常用处理函数

**

1.len( )函数

用len( )函数计算字符串的长度

python perl 字符处理 python字符处理函数_Python


2.strip( )函数

删除字符串两边的空白符(包括:’\n’、’\t’、’\r’)

注:只能对字符串两边做处理,不能对中间部分进行处理

python perl 字符处理 python字符处理函数_Python_02


3.capitalize( )函数

将字符串首字母大写

python perl 字符处理 python字符处理函数_字符串_03


4.upper( )函数

用upper( )函数将字符串全部变为大写

python perl 字符处理 python字符处理函数_Python_04


5.find( )函数

用find( )函数查找指定字符在字符串中的位置

注:若找不到指定字符,则返回值-1

python perl 字符处理 python字符处理函数_Python_05


注:find与index功能相似,但index若找不到指定字符会引发异常

6.startswith( )函数

用startswith( )函数判断字符串的开头字符

python perl 字符处理 python字符处理函数_Python_06


7.endswith( )函数

用endswith( )函数判断字符串的结尾字符

python perl 字符处理 python字符处理函数_指定位置_07


8.center( )函数

用center( )函数将字符串以指定宽度居中,其余部分以特定字符填充

center(指定长度,‘特定字符’ )

python perl 字符处理 python字符处理函数_Python_08


9.rjust( )函数

用rjust( )函数将字符串以指定宽度放在右侧,其余部分以特定字符填充

rjust(指定长度,‘特定字符’ )

python perl 字符处理 python字符处理函数_python perl 字符处理_09


10.字符串的切片


  • 可以选取字符串中连续的一段:eg : str1[1:4] 右端不包括在查找范围之内
  • 可间断选取字符串中字符:eg:str1[0::2] 其中2为步长,:代表直到最后
  • 可以将字符串倒序: eg:str1[::-1] 负数步长代表从后向前查找

    11.isdigit( )函数
    用isdigit( )函数判断字符串是否由数字组成

    12.isalpha( )函数
    用isalpha( )函数判断字符串是否由字母组成

    13.isalnum( )函数
    用isalnum( )函数判断字符串是否由数字和字母组成

    就更这么多啦,如有错误,欢迎指正呀!