py--字符串

目錄

1、字符串種類

2、字符串轉義字符

3、字符串運算符

4、字符串格式化

5、常用內置函數以及自定義該函數

5.1、center:返回指定寬度居中的字符

5.2、index():檢測字符串中是否包含子字符串

5.3、find():檢測字符串中是否包含子字符串

5.4、額外:findall():找到字符串中的所有子字符串的位置

5.5、zfill():返回指定長度字符串,前面補充0

5.6、lower():轉換爲小寫字母

5.7、capwords()和title():每個單詞首字母進行大寫操作

5.8、count():統計字符串中某個字符出現次數

5.9、strip() rstrip() lstrip():移除空白字符

5.10、split() ----可以將字符串轉換爲列表

5.11 、join()---可以將列表轉換爲字符串

5.12、replace():替換字符串

5.13、string函數


 


1、字符串種類

  • 1、unicode-------》type類型在python3中顯示的是str類型
  • 2、bytes

程序:

>>> "abc"
'abc'
>>> type("abc")
<class 'str'>
>>> "abc".encode("gbk")
b'abc'
>>> type("abc".encode("gbk"))
<class 'bytes'>
>>>
>>> type("中國")
<class 'str'>
>>> type("中國".encode("utf-8"))
<class 'bytes'>
>>> type("中國".encode("utf-8").decode("utf-8"))
<class 'str'>
>>> print("中國".encode("gbk"))
b'\xd6\xd0\xb9\xfa'
>>>

提問1:爲什麼字符串有2種數據類型,爲什麼存在bytes類型的數據

答案:只要不是在內存中使用,都是使用的bytes類型,在寫文件時,也是使用的bytes類型。網絡傳輸也是使用bytes類型。

在計算機的內存中,統一使用unicode編碼,當需要保存到硬盤或者需要傳輸的時候,就轉換爲bytes編碼用記事本編輯的時候,從文件讀取的utf-8字符被轉換爲unicode字符到內存裏面,編輯完成後,保存的時候再把unicode轉換成utf-8保存到文件中

提問2:bytes類型怎麼使用?

示例:

>>> s=b"abc"
>>> type(s)
<class 'bytes'>
>>> ss=b"光榮之路"
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> ss="光榮之路".encode("utf-8")
>>> s
b'abc'
>>> ss
b'\xe5\x85\x89\xe8\x8d\xa3\xe4\xb9\x8b\xe8\xb7\xaf'
>>>
>>> ss.decode("utf-8")
'光榮之路'
>>>
>>> s="光榮之路".encode("utf-8").decode("utf-8").encode("gbk")
>>> s
b'\xb9\xe2\xc8\xd9\xd6\xae\xc2\xb7'
>>>

解釋說明:

1)當字符串爲字母時,可以直接加一個b就可以轉換成bytes類型

2)當字符串爲中文時,轉換爲bytes類型,需要使用encode纔可以轉換,直接寫b的形式會報錯。

提問3:怎麼判斷該變量是否爲字符串

答案:使用isinstance函數,一般應用在函數傳參數時判斷傳參的類型。

示例:

>>> def add(a,b):
...     if (not isinstance (a,str)) or (not isinstance(b,str)):
...         return None
...     else:
...         return a+b
...
>>> add("hello",1)
>>> print(add("hello",1))
None
>>> print(add("a","b"))
ab
>>>

2、字符串轉義字符

示例:

1)\(續行符)

>>> print("i am a good boy \
... i hava a ball")
i am a good boy i hava a ball
>>>

2)\\:輸出\

>>> print("i am a good boy,\\tomoto" )
i am a good boy,\tomoto
>>>
>>> path="e:\\test\\a.txt"
>>> print(path)
e:\test\a.txt
>>> path=r"e:\test\a.txt"
>>> print(path)
e:\test\a.txt
>>>

3)\n:換行符

>>> print("i am a \n boy")
i am a
 boy
>>>
>>> a="a\nb"
>>> print(a)
a
b
>>> a="a\\nb"
>>> print(a)
a\nb
>>>

4)\r :回車

>>> import os
>>> os.linesep
'\r\n'
>>>
  • Windows默認的回車是:\r\n
  • Linux默認的回車是:\n
  • Mac默認的回車是:\n

5)使用單引號、雙引號的方法

  • 外部用單引號,內部用雙引號
  • 外部 用雙引號,內部用單引號
  • 或者內外部相同,用轉義符號

示例:

>>> s="i am' ade"
>>> s
"i am' ade"
>>> s='i " dei'
>>> s
'i " dei'
>>> a='i am \' a boy'
>>> a
"i am ' a boy"
>>>

3、字符串運算符

運算符

描述

+

字符串進行拼接

*

字符串重複操作

[]

通過字符串的索引進行查詢數據

[:]

截取字符串中的一部分數據

r

 

%

格式化字符串

in / not in

成員字符串,如果原字符串中包含該字符,返回true,否則,返回false

示例:

>>> a="hello"
>>> b="world"
>>> a+b
'helloworld'
>>> a*2
'hellohello'
>>> a[-1]
'o'
>>> a[0]
'h'
>>> a[2:6]
'llo'
>>> a[-3:-1]
'll'

>>> "mingtian" in a
False
>>> "a" in a
False
>>> "hel" in a
True
>>>
>>> s="abcdef"
>>> s[1:4]
'bcd'
>>> s[-3:-6:-1]
'dcb'
#如何取出“fdb呢”,有以下幾種方案
>>> s[-1:-6:-2]
'fdb'
>>>
>>> s[-1:0:-2]
'fdb'
>>>
>>> s[::-2]
'fdb'
>>>

注意事項:

  • 字符串是不可改變的類型,通過id地址可以看出來

當2個不同的變量,都指向一個字符串的內存地址時,兩個變量的id值是一樣的。

4、字符串格式化

示例:

>>> print("你的名字爲%s,你的體重爲%d kg"%("耿志慧",70))
你的名字爲耿志慧,你的體重爲70 kg
>>>

5、常用內置函數以及自定義該函數

5.1、center:返回指定寬度居中的字符

語法:

str.center(width,fillchar)

自定義程序:

#coding=utf-8

def center(orginal_str,width,fillchar_str):
    if (not isinstance(orginal_str,str)) or (not isinstance(width,int))\
       or (not isinstance(fillchar_str,str)):
        return None

    if len(orginal_str)>=width:
        return orginal_str
    else:
        result=""  #最後返回的字符串
        length_diff=width-len(orginal_str)  #判斷最後需要填充幾個
        if length_diff%2==0:
            result=fillchar_str*(length_diff//2)+orginal_str+\
                    fillchar_str*(length_diff//2)
            return result
                    
        else:
            result=fillchar_str*(length_diff//2)+orginal_str+\
                    fillchar_str*(length_diff-length_diff//2)
            return result


print(center("hello",10,"*"))
print(center("hello",3,"-"))

結果:

============================== RESTART: E:\a.py ==============================

**hello***

hello

>>>

 

5.2、index():檢測字符串中是否包含子字符串

定義:

index()方法檢測字符串中是否包含子字符串str,如果指定beg(開始)和end(結束)範圍,則檢查是否包含在指定範圍內,該方法和python中的find()方法一樣,只不過如果str不再string中會報一個異常。

語法:

str.index(sub,a,b)

自定義程序:

#coding=utf-8

def index(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str))\
       or (not isinstance(start_position,int))or (not isinstance(end_position,int)):
        return None
    if end_position==None:
        end_position=len(s)

    for i in range(start_position,end_position):
        if s[i:i+len(sub)]==sub:
            return i
    raise ValueError("substring not found")


print(index("hello word","or",1,10))    

#方法2:用while實現

def index(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str))\
       or (not isinstance(start_position,int))or (not isinstance(end_position,int)):
        return None
    if end_position is None:
        end_position=len(s)
    
    

    index=start_position

    while index <=end_position:
        if s[index:index+len(sub)]!=sub:
            index+=1
        else:
            return index
            break
            
            
    raise ValueError("substring not found")

print(index("hello word","rd",1,11))

 

5.3、find():檢測字符串中是否包含子字符串

定義:

find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,如果指定範圍內如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

語法:

str.find(sub,a,b)

sub:要查找的子字符串

a:查找索引的開始位置

b:查找索引的結束位置

示例:

#coding=utf-8

def find(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str)):
        return None
    if end_position==None:
        end_position=len(s)

    for i in range(start_position,end_position):
        if s[i:i+len(sub)]==sub:
            return i
            break
    else:
        return -1


print(find("hello word","el"))
print(find("hello word","diwe"))

#方法2:用while實現

def find(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str)):
        return None
    if end_position is None:
        end_position=len(s)
   
    index=start_position

    while index <=end_position:
        if s[index:index+len(sub)]!=sub:
            index+=1
        else:
            return index
            break
            
            
    else:
        return -1
    
print(find("hello word","rd"))
print(find("djiwejskjdiwe","dwewoejj"))

5.4、額外:findall():找到字符串中的所有子字符串的位置

自定義程序:

#coding=utf-8

def findall(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str)):
        return None
    if end_position==None:
        end_position=len(s)
    result=[]
    for i in range(start_position,end_position):
        if s[i:i+len(sub)]==sub:
            result.append(i)

    if result==[]:
        return -1
    else:
        return result
  

print(findall("hello word hello word","wor"))
print(findall("hello word wdiw","diwe"))

#方法2:用while實現

def findall(s,sub,start_position=0,end_position=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str)):
        return None
    if end_position is None:
        end_position=len(s)
    
    

    index=start_position
    result_2=[]

    while index <=end_position:
        if s[index:index+len(sub)]!=sub:
            index+=1
        else:
            result_2.append(index)
            index=index+len(sub)
            
            
    if result_2==[]:
        return -1
    else:
        return result_2
    
print(findall("hello word rddiw rd","rd"))
print(findall("djiwejskjdiwe","dwewoejj"))

5.5、zfill():返回指定長度字符串,前面補充0

定義:

Python zfill() 方法返回指定長度的字符串,原字符串右對齊,前面填充0。

語法:

str.zfill(width)

width:長度

注意事項:

  • 如果長度大於字符串本身,則左邊填充0,字符串右對齊,然後填充夠該長度的字符
  • 如果長度小於字符串本身,則返回該字符串。

自定義程序:

#coding=utf-8

def zfill(s,width):
    if (not isinstance(s,str)) or (not isinstance(width,int)):
        return None

    if width<=len(s):
        return s
    else:
        result=""
        result="0"*(width-len(s))+s
        return result

print(zfill("hello",20))
print(zfill("abcdwjewiemsd",6))

結果:

============================== RESTART: E:\a.py ==============================

000000000000000hello

abcdwjewiemsd

>>>

5.6、lower():轉換爲小寫字母

定義:

將字符串中的小大寫字母轉換成小寫

語法:

str.lower()

自定義程序:

#coding=utf-8

def lower(s):
    if not isinstance(s,str):
        return None
    result=""
    for i in s:
        if i>="A" and i<="Z":
            result+=chr(ord(i)+32)
        else:
            result+=i

    return result

print(lower("DJIWEdjiwei,,DIWEewejw392323"))

結果:

============================== RESTART: E:\a.py ==============================

djiwedjiwei,,diweewejw392323

>>>

 

5.7、capwords()和title():每個單詞首字母進行大寫操作

定義:

將每個單詞的首字母進行大寫操作

語法:

string.capwords(str) str.title()

自定義程序:

#coding=utf-8
import string
def title(s):
    if  not isinstance(s,str):
        return None

    result_list=[]
    for k in s.split():
        if k[0]>="a" and k[0]<="z":
            result_list.append(chr(ord(k[0])-32)+k[1:])

    return " ".join(result_list)

print(title("i am a boy!"))

結果:

============================== RESTART: E:\a.py ==============================

I Am A Boy!

>>>

有漏洞,後期在寫。

 

5.8、count():統計字符串中某個字符出現次數

定義:

count() 方法用於統計字符串裏某個字符出現的次數。可選參數爲在字符串搜索的開始與結束位置。

語法:

str.count(sub,a,b)

sub:要統計的子字符串

a:要開始統計的索引位置

b:要結束統計的索引位置

自定義程序:

#coding=utf-8

def count(s,sub,a=0,b=None):
    if (not isinstance(s,str)) or (not isinstance(sub,str)):
        return None
    if b==None:
        b=len(s)

    times=0

    #定義一個索引位置
    index=a

    while index<=b:
        if s[index:index+len(sub)]==sub:
            times+=1
            index=index+len(sub)
        else:
            index+=1

    return times

print(count("aabaaaa","aa"))
print(count("aaaaaa2i3aaeiaa","aa",1,8))

結果:

============================== RESTART: E:\a.py ==============================
3
2
>>>

5.9、strip() rstrip() lstrip():移除空白字符

定義:

strip() :用於移除字符串頭尾指定的字符(默認爲空白符,例如:"/n /t /r")或字符序列。

rstrip():刪除字符串中右邊指定的字符(默認爲空白符,例如:"/n /t /r")或者字符序列

lstrip():刪除字符串中左右指定的字符(默認爲空白符,例如:"/n /t /r")或者字符序列

語法:

str.strip([char])

[char]:要刪除的字符序列

注意事項:

  • 其中空白字符串包含:“\n”,“\t”(橫向座標符),“\r”(回車)和空白(英文空白)
  • 該方法只能刪除開頭或是結尾字符,不能刪除中間部分的字符
  • 當要刪除的字符串在末尾或者開始不存在時,則返回原字符串,代表沒有進行操作

算法:

'''

1、首先定義如果不傳要刪除的字符序列,則默認爲: \r\t\n

2、定義一個存放最終結果的字符串result,定義result最初的索引位置(start_index)和最後的索引位置(end_index),只要找到這兩個位置,則result就可以採用切片的方法找到

3、遍歷這個字符串,採用索引的方式,正序查找,倒敘查找,如果碰到元素不是去除元素中的一個時,則記錄下start_index,end_index的位置。

'''

#coding=utf-8

def strip(s,char):
    if (not isinstance(s,str)):
        return None
    
    if char==None:
        char=" \r\n\t"

    result=""
    start_index=0  #最終結果的索引位置
    end_index=-1   #最終結果的索引位置

    for i in range(len(s)):
        
        if s[i] not in  char:   #當元素不是去除元素中的一個時,記錄索引位置
            start_index=i
            break
        
    
    for k in range(-1,-len(s),-1):
        if s[k] not in char:  #當元素不是去除元素中的一個時,記錄索引位置
            end_index=k
            break
    

    result=s[start_index:end_index]
    return result
        
print(strip("   8w99392383    "," "))
print(strip('*#*dwei*#*diwi3  *#*','*#*'))

 

5.10、split() ----可以將字符串轉換爲列表

定義:

split()通過指定分隔符對字符串進行切片,如果參數num 有指定值,則僅分隔 num 個子字符串

語法:

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

str:指定的分隔符,默認爲所有的空白字符,包括空格、換行(\n)、製表符(\t)等。

num:分割次數

返回值:返回分割後的字符串列表

算法:

"""

1、用一個變量記錄遍歷字符的位置 index

2、每次遍歷字符串,如果從當前字符串開始加上分割符長度不能等於分割符,則當前字符拼接到一個字符串,更新index+=1,直到

碰到分割字符串,index+=拼接字符串長度

3、把拼接的字符串放在一個列表

4、重複以上過程,直到分割次數爲0

"""

#coding=utf-8

def split(s,split_str=None,times=None):
    if split_str == None:
        split_str = " "
    if times == None:
        times = s.count(split_str)
        
    index = 0
    split_str_length = len(split_str)
    result = []
    while times > 0:
        temp = ""
        for i in range(index,len(s)):
            
            if s[i:i+split_str_length] != split_str:
                temp += s[i]
                index += 1
            else:
                index += split_str_length
                break
        result.append(temp)
        times -= 1
    result.append(s[index:])
    return result
print(split("a1*b*c*d","*"))
print(split("a1*b*c*d","*",2))
print(split("a1 b c d"))
print(split("a1**b**c**d","**"))

5.11 、join()---可以將列表轉換爲字符串

定義:

Python join() 方法用於將序列中的元素以指定的字符連接生成一個新的字符串。

語法:

str.join(sequence)

sequence: 用字符串要連接的序列,序列可以爲字符串,列表和元組

返回值:返回通過指定字符連接序列中元素後生成的新字符串

自定義程序:

#coding=utf-8
import collections

def join(seq,join_str=""):
    if (not isinstance(seq,collections.Sequence)) or (not isinstance (join_str,str)):
        return None
   
        
    temp=""
    for i in range(len(seq)-1):
        if not isinstance (seq[i],str):
            raise TypeError 
        temp+=seq[i]+join_str

    temp+=seq[-1]
    return temp

#print(join([1,2,3,4],"*"))
print(join(["1","2","a","d"],"-"))
print(join(("a","b","c","d")))

5.12、replace():替換字符串

定義:

將字符串中的舊字符串替換成新字符串,如果指定第三個參數max,則替換不超過max次

語法:

str.replace(old,new,max)

old:將要被替換的字符串

new:新的字符串,用於替換old的字符串

max:替換的最大次數

自定義程序:

#coding=utf-8

def replace(s,old_str,new_str):
    if (not isinstance(s,str)) or (not isinstance(old_str,str)) or (not isinstance(new_str,str)):
        return None

    result=""
    index=0

    while index <len(s):
        if s[index:index+len(old_str)]==old_str:
            result+=new_str
            index=index+len(old_str)
        else:
            result+=s[index]
            index+=1

    return result

print(replace("abcdwieidiwe","w","123"))
print(replace("abcdwe12diwe12djiwei12","12","www."))

結果:

============================== RESTART: E:\a.py ==============================

abcd123ieidi123e

abcdwewww.diwewww.djiweiwww.

adieiedjiei

>>>

5.13、string函數

string函數有很多常用的函數,查看string函數有:

>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

示例:

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.digits
'0123456789'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.capwords
<function capwords at 0x00000249F30CB488>

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章