1. 程式人生 > >字符串操作二

字符串操作二

統計 class類 開頭 () 首字母 title translate name lines

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‘

字符串操作二