字符串操作二

简介:

s.find()函数

可在指定字符串范围内查找子字符串出现的位置
S.find(substr, [start, [end]])
#返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。 start和end作用就相当于在S[start:end]中搜索
代码示例1

    s = 'My is good!'
    print s.find('My')
    print s.find('M')
    print s.find('a',3)
        #结果:
        0
        0
        -1

s.index()函数

可在指定字符串范围内查找子字符串出现的位置,找不到则返回错误
S.index(substr, [start, [end]])
#与find()相同,只是在S中没有substr时,会返回一个运行时错误

def print_str():
    s = 'My is good!'
    print s.index('is',0,2)
    #   提示:
        Traceback (most recent call last):
  File "D:/TOOL/PycharmProjects/python/December/Monday.py", line 21, in <module>
    print_str()
  File "D:/TOOL/PycharmProjects/python/December/Monday.py", line 10, in print_str
    print s.index('is',0,2)
ValueError: substring not found

print s.index('is',1)
#结果:
3

s.rfind()函数

可在指定字符串范围内查找子字符串出现的位置
S.rfind(substr, [start, [end]])
#返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号

    s = 'My is good!'

    print s.rfind('is',1)
    print s.rfind('My',1,3)

S.rindex()函数

可在右侧指定字符串范围内查找子字符串出现的位置,找不到则报错。
S.rindex(substr, [start, [end]])#找不到则会报错误
代码示例:

    s = 'My is good!'
    print s.rindex('is',1,20)

S.replace() 函数

实现替换字符串的指定内容
S.replace(oldstr, newstr, [count])
#把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换

    s = 'My is good!'
    print s.replace("My","I")
    #结果:
    I is good!

S.expandtabs()函数

可以将tab替换为指定的空格数量
S.expandtabs([tabsize])
#把S中的tab字符替换为空格,每个tab替换为tabsize个空格,默认是8个

print s1.expandtabs(1)

S.split() 函数

可以用指定字符串将字符串进行分割字符串的分割和组合:
S.split([sep, [maxsplit]])
#以sep为分隔符,把S分成一个list, maxsplit表示分割的次数。默认的分割符为空白字符

    s = 'My is good!'
    print s.split()
        结果:['My', 'is', 'good!']

S.rsplit ()函数

可以用指定字符串从右侧将字符串进行分割
S.rsplit([sep,
[maxsplit]]

    s = 'My *is *good!'
    print s.split()
    print s.rsplit("*")
    print s.rsplit("*", 1)
        结果:
        ['My', '*is', '*good!']
['My ', 'is ', 'good!']
['My *is ', 'good!']

S.splitlines()函数

按照分隔符分割字符串
S.splitlines([keepends])
#把S按照行分割符分为一个list, keepends是一个bool值,如果为真每行后而会保留行分割符。

    s1 = '1\n2\n'
    print s1.splitlines()
    print s1.splitlines(1)
    #   结果:
        ['1', '2']
    ['1\n', '2\n']

S.join()函数

将列表拼接为字符串

    s = 'My is good!'
    s_list = s.split()
    print s_list
    print "".join(s_list)
        #结果:
        ['My', 'is', 'good!']
Myisgood!

S.startswith()函数

判断字符串是否以某个字符串为开头

    s = 'My is good!'
    print s.startswith('My')
    if s.startswith("My"):
        print "yes ,the String start \"My\" "
        #结果:
    True
yes ,the String start "My" 

S.endswith()函数

判断字符串是否以某个字符串为结尾

    s = 'My is good!'
    print s.endswith('good!')
    #   结果:
        True

n

判断字符串中是否有某个字符串

    s = ' 2332 My 323 is good!'
    res = []
    for i in s:
        if i in "0123456789":
            continue
        else:
            res.append(i)
    print "".join(res)
    结果:
      My  is good!

S.isalpha()

该函数的作用是,如果S中所有的字符都是由字母组成,并且S至少有一个字符,则返回True,否则返回False

s = "dddd"
    if s.isalpha():
        print "句子有字母"
    else:
        print "句子没有字母"

S.isalnum()

该函数的作用是,如果S中所有的字符都是由字母或数字组成,并且S至少有一个字符,则返回True,否则返回False

 w = "12323"
    if w.isalpha():
        print "句子有字母"
    else:
        print "句子没有字母"

S.isdigit()

该函数的作用是,如果S中所有的字符都是由数字组成,并且S至少有一个字符,则返回True,否则返回False

num = "123"
if num.isdigit() :
    print "all characters in  are digits"
else :
   print "all characters in num  aren't digits

S.isspace()

该函数的作用是,如果S中所有的字符都是由空格组成,并且S至少有一个字符,
则返回True,否则返回False

    num = " "
    if num.isspace():
        print "all characters in num are whitespace"
    else:
       print "all characters in num aren't whitespace"

S.islower()

该函数的作用是,如果S中所有的字母都是小写,并且S至少有一个字母,则返回True,否则返回False。

    s = "My  is good!"
    print "".join(s).islower()
        结果:
        False

S.isupper()

该函数的作用是,如果S中所有的字母都是大写,并且S至少有一个字母,则返回True,否则返回False

    s = "MW"
    print "".join(s).isupper()
        结果:
        True

S.istitle()

该函数的作用是,检测字符串S中所有的单词拼写首字母是否为大写字母,
其他为小写字母,并且S至少有一个字母,则返回True,否则返回False。

    s = "My name is python"
    print "".join(s).istitle()
    s1 = "My Name Is Python"
    print "".join(s1).istitle()
        结果:
        False
True

S.maketrans() 函数

String.maketrans(from, to)
#返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的

t=string.maketrans('abc','ABC')
print 'abc123'.translate(t,'123')
结果:
ABC

isinstance()函数

该方法表示判断对象object是否是class-or-type-or-tuple的实例或者是子类。
class-or-type-or-tuple表示可以是class类型、 type类型,也可以是很多类型组成的tuple。


s2 = u"this is a test"
#判断变量s2是否是Unicode类型
print isinstance(s2, unicode)
list1 = [1,2,3,4,5]
#判断变量list1是否是list类型
print isinstance(list1, list)
num = 12
#判断变量num是否是int类型
print isinstance(num, int)
f = 12.9
print isinstance(f, int)
if isinstance(f, (int, float, str, list)) :
    print u"变量f的类型属于(int, float, str, list)中的一种。 "
else :
 print u"变量f的类型不属于(int, float, str, list)中的一种。 "
class A(object) :
    pass
#判断类A是否是object类型
print isinstance(A, object)
结果:
True
True
True
False
变量f的类型属于(int, float, str, list)中的一种。 
True

string.atoi(s [,base])

该方法表示将数字型字符串s转换成指定进制base的整型数并返回结果,但原字符串并未被改变。base:默认为10,如果指定为0,表示转为八进制,如果是16,表示将s转换成十六进制。


s = "18"
#数字型字符串转十进制整数
d = string.atoi(s)
print d
#转八进制
o = string.atoi('011', 8)
print o
#转十六进制
h = string.atoi('0x11', 16)
print h
结果:
18
9
17

S.count()函数

用于在字符串范围内进行出现次数统计
S.count(substr, [start, [end]]) #计算substr在S中出现的次数

    s = "My name is python"
    print  s.count("n")
        结果:
         2
    s = "sssscccddddeeewererere"
    res = {}
    for i in s:
         res[i] = s.count(i)
    print res
    结果:
    {'c': 3, 'e': 7, 'd': 4, 's': 4, 'r': 3, 'w': 1}

练习

str = "abcdefghijklmn"
#以步长为2切取下标2-9的子序列
>>>str[2:9:2]
'cegi'
#使用“+”连接两字符串
>>>str[2:5] + str[10:14]
'cdeklmn'
#字符串重复打印3次
>>>str[1:3] * 3
'bcbcbc'
>>>"*" * 5
'*****'
#查看字符'c'是否存在字符串str中,存在返回true,不存在返
货false
>>>'c' in str
True
>>>'z' in str
False
>>>"abc" in str
True
#查看"12"是否不在字符串str中,不存在返回true,存在返回
false
>>>"12" not in str
True
#以步长为1,从右向左显也就是将原字符串翻转。
>>>str[::-1]
'nmlkjihgfedcba'
#获取字符串中最大的字符,
以字符的ASCII码的值为比较
依据
>>>max(str)
'n'
#获取字符串中最小的字符
>>>min(str)
'a'









本文转自 知止内明 51CTO博客,原文链接:http://blog.51cto.com/357712148/2060812,如需转载请自行联系原作者
目录
相关文章
|
1月前
|
C++
18字符串处理函数
18字符串处理函数
12 0
|
2月前
|
C++
c++字符串操作
c++字符串操作
29 0
|
10月前
|
C++
C/C++字符串处理函数
C/C++字符串处理函数
|
C++ 容器
C++ 字符串操作
文章目录 1.1 C++ 字符串操作 2.2字符数组的常用操作 2.3遍历字符数组的字符 3.标准库类型string 3.1 定义和初始化 3.2 string的操作 1)读写操作 2)使用`getline`读取一整行 3)string的方法操作 4)字符串和string相加 3.3处理string对象中的字符
|
开发者 索引 Python
字符串操作|学习笔记
快速学习字符串操作
45 0
字符串操作|学习笔记
|
安全 Shell C语言
C语言_10 字符、字符串操作
字符、字符串及一些函数
121 0
C语言_10 字符、字符串操作
|
存储 编译器
字符串操作函数详解
字符串操作函数详解
字符串操作函数详解

热门文章

最新文章