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'
>>>

 

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