天天看點

python字元串類型字元串類型

目錄

  • 字元串類型
    • 一、字元串(str)
      • 1.1作用
      • 1.2定義
    • 二、如何用
    • 三、字元串類型的内置方法
      • 3.1 優先掌握
      • 3.2需要掌握
      • 3.3其他内置方法

字元串類型

一、字元串(str)

1.1作用

可以用來表示姓名,愛好等

1.2定義

字元就相當于一個一個的山楂,字元串相當于一個糖葫蘆。字元串就向糖葫蘆一樣将山楂,串聯起來。字元串就像是一串被串聯起來的字元,在單引号,雙引号或者三引号内包裹的一串字元。

  1. 普通字元串的定義方式
name1 = 'chen'
name2 = "nick"
print(id(name1))
print(type(name1))
print(name1)
#輸出:
2793468686640
<class 'str'>
chen


print(id(name2))
print(type(name2))
print(name2)
#輸出:
2659224937200
<class 'str'>
nick                
  1. 三引号内的字元串定義:

    ​ 需要注意的是,

    ​ ==三引号内的字元是可以換行的,換行的時候會輸出換行==

name3 = """chen
nick
"""

print(name3)
#輸出:
chen
nick



name4 = '''chen
nick
'''
print(name4)
#輸出:

chen
nick


                
  1. 二進制字元串的定義方式
#列印出來bytes,二進制類型的定義方式。
s=b'chen'
print(s)
print(type(s))
#輸出:
b'chen'
<class 'bytes'>
                
  1. 帶有特殊意義的符号定義字元串
    s='ch\nen'  #\n換行
    print(s)
    print(type(s))
    #輸出:
    ch
    en
    <class 'str'>                
    s='ch\ten'  #\t縮進4位
    print(s)
    print(type(s))
    #輸出:
    ch   en
    <class 'str'>                
    s='ch\ren' # 原位置列印
    print(s)
    print(type(s))
    #輸出:
    en
    <class 'str'>
                    
    s='c\nh\re\tn'
    print(s)
    print(type(s))
    #輸出:
    c
    e    n
    <class 'str'>
    
    w=r'c\nh\re\tn'   #原生列印,取消特殊字元的意義
    print(w)
    print(type(w))
    
    #輸出:
    c\nh\re\tn
    <class 'str'>                

二、如何用

字元串隻能加(+),乘(*)以及邏輯比較

字元串的拼接,即重新申請一個小空間把倆個字元串都拷貝到一份後在拼接。而不是把一個小空間的變量值複制到另外一個變量的小空間内,然後拼接。

msg2 = "my name is 'chen'"
msg3 = "my name is 'chen'"
print(msg2+msg3)
#輸出:
my name is 'chen'my name is 'chen'                

輸出:my name is 'chen'my name is 'chen'

注意:==如果字元串内有引号,則包裹字元串的引号和字元串内部的引号不能相同==

name = 'chen'
print(name * 10)

#輸出:

chenchenchenchenchenchenchenchenchenchen                

注意:==字元串的乘法隻能乘以數字。==

msg1 = 'hello'
msg2 = 'z'
print(msg1 > msg2)
#輸出:
False                

注意:==字元串比較大小,按照ASCII碼比較,比較的是字母的順序==

三、字元串類型的内置方法

3.1 優先掌握

  1. 按索引取值(隻能取不能改變)
    msg = 'hello python'
    print(f"索引為6:{msg[6]}")
    輸出:
    索引為6: n                
  2. 切片(顧頭不顧尾)
    mag = 'hello chen'
    ###### h  e  l  l  o     c  h  e  n
    ###### 0  1  2  3  4  5  6  7  8  9  從前往後的索引序号
    ######-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 從後往前的索引序号
    ########顧頭不顧尾
    
    
    print(mag[3])
    #輸出 l
    print(mag[:])
    #輸出 hello chen
    print(mag[3:])
    #輸出 lo chen
    print(mag[:3])
    #輸出 hel
    print(mag[3:8])
    #輸出lo ch
    print(mag[::])
    #輸出hello chen
    print(mag[::3])
    #輸出 hlcn
    print(mag[:3:])
    #輸出 hel
    print(mag[3::])
    #輸出 lo chen
    print(mag[3:8:2])# 步長位2
    #輸出 l h
    print(mag[3:8:])
    #輸出 lo ch
    print(mag[3::2])
    #輸出 l hn
    print(mag[:8:2])
    #輸出 hloc
    print(mag[-2:-5:1])#正序
    #輸出
    print(mag[-2:-5:-1])#倒叙
    #輸出ehc
    print(mag[::-1])
    #輸出nehc olleh                
  3. 長度len
    mag = 'hello chen'
    print(len(mag))
    #輸出:
    10
                    
  4. 成員變量in or not in
    mag = 'hello chen'
    print('hello' in mag)#判斷字元是否在字元串中
    # 輸出:True
    print('chen' not in mag)
    # 輸出:False
                    
  5. 移除空白strip(移除的字元必須在兩端)
    mag= '     chenshuai    '
    print(mag.strip())#去掉倆邊空格
    ##輸出:
    chen shuai
    
    
    mag = '&&&hello chen'
    
    print(mag.strip('&'))#指定多個字元,可以去掉
    #輸出:hello chen
    print('&&&hello chen'.strip('& '))
    #輸出:hello chen                
  6. 切分split(預設以空格切割字元串)
    info="chen shuai"
    print(info.split())#預設以空格為切割符
    #輸出:
    ['chen','shuai']
    
    
    
    
    ##split()選中一些符号或者字元
    info = "python:male:30"
    list1 = info.split(":")
    list2 = info.split(":", 0)  # 表示不切
    list3 = info.split(":", 1)  # 表示以':'為切割符,隻切割第一個
    list4 = info.split(":", 2)  # 表示以':'為切割符,隻切割前倆個
    list5 = info.split(":", -1)
    print('list1:',list1)
    print('list2:',list2)
    print('list3:',list3)
    print('list4:',list4)
    print('list5:',list5)
    
    輸出:
    list1: ['python', 'male', '30']
    list2: ['python:male:30']
    list3: ['python', 'male:30']
    list4: ['python', 'male', '30']
    list5: ['python', 'male', '30']                
  7. 循環
    mag = 'hello python'
    for i in mag:
        print(i)
    
    
    
    #輸出 :
    h
    e
    l
    l
    o
    
    p
    y
    t
    h
    o
    n                

3.2需要掌握

  1. Istrip&rstrip
    mag = '&&hello python&&'
    print(mag.strip('&'))
    print(mag.lstrip('&'))##去除首部的
    print(mag.rstrip('&'))## 取出尾部的
    輸出:
    hello python
    hello python&&
    &&hello python                
  2. lower&upper
    mag = 'HELLO python'
    print(mag)
    print(mag.upper())##大寫
    print(mag.lower())## 小寫
    
    #輸出:
    HELLO python
    HELLO PYTHON
    hello python                
  3. startswith&endswith
    mag = 'HELLO python'
    print(mag.startswith('HELLO'))##檢測以什麼開頭
    print(mag.endswith('python'))## 檢測以什麼結尾
    #輸出:
    True
    True
                    
  4. rsplit
    ## 從右邊開始切割
    mag = 'hello:python:chen'
    print(mag.rsplit(':'))
    print(mag.rsplit(':',1))
    #輸出:
    ['hello', 'python', 'chen']
    ['hello:python', 'chen']                
  5. join
    # 拼接
    lis = [1,2,'19']
    print(':'.join(lis))  # 報錯,數字不可和字元串拼接
                    
    # str之join()
    lis = ['chen', 'male', '19']
    
    print(':'.join(lis))
    #輸出
    chen:male:19                
  6. replace
    msg = 'hello chen'
    print(msg.replace('chen','python'))#替換
    #輸出:
    hello python                
  7. isdigit
    #檢測是否為整數
    salary = '111'
    print(salary.isdigit()) 
    #輸出: True
    
    salary = '111.1'
    print(salary.isdigit())  
    #輸出: False                
  8. isalpha判斷是否為字元

3.3其他内置方法

  1. find|rfind|index|rindex|count
  2. center|ljust|rjust|zfill
  3. expandtabs
  4. captalize|swapcase|title
  5. is系列

1.find()、rfind()、index()、rindex()、count()

  • find/rfind求索引,find('字元'),找到第一個,傳回索引,找不到傳回-1
  • index求索引 ,index('字元'),找到第一個,傳回索引,找不到報錯
# str之find()、rfind()、index()、rindex()、count()
msg = 'my name is tank, tank shi sb, hha'

print(f"msg.find('tank'): {msg.find('tank')}")  # 找不到傳回-1
print(f"msg.find('tank',0,3): {msg.find('tank',0,3)}")
print(f"msg.rfind('tank'): {msg.rfind('tank')}")  # 找不到傳回-1
print(f"msg.index('tank'): {msg.index('tank')}")  # 找不到報錯
print(f"msg.rindex('tank'): {msg.rindex('tank')}")  # 找不到報錯
      

print(f"msg.count('tank'): {msg.count('tank')}")
msg.find('tank'): 11
msg.find('tank',0,3): -1
msg.rfind('tank'): 17
msg.index('tank'): 11
msg.rindex('tank'): 17
msg.count('tank'): 2
           

2.center()、ljust()、rjust()、zfill()

  • center以字元為中心
  • ljust讓字元靠左
  • rjust讓字元靠右
  • zfill字元前填充多少0
# str之center()、ljust()、rjust()、zfill()
print(f"'info nick'.center(50,'*'): {'info nick'.center(50,'*')}")
print(f"'info nick'.ljust(50,'*'): {'info nick'.ljust(50,'*')}")
print(f"'info nick'.rjust(50,'*'): {'info nick'.rjust(50,'*')}")
print(f"'info nick'.zfill(50): {'info nick'.zfill(50)}")  # 預設用0填充
'info nick'.center(50,'*'): ********************info nick*********************
'info nick'.ljust(50,'*'): info nick*****************************************
'info nick'.rjust(50,'*'): *****************************************info nick
'info nick'.zfill(50): 00000000000000000000000000000000000000000info nick
           

3.expandtabs()

擴張,隻針對字元串裡面有\t的字元串

# str之expandtabs()
print(f"a\\tb\\tc: %s"%('a\tb\tc\t'))  # 預設制表符8個空格
print(f"'a\\tb\\tc'.expandtabs(32): %s"%('a\tb\tc\t'.expandtabs(32)))
a\tb\tc: a  b   c   
'a\tb\tc'.expandtabs(32): a                               b                               c                               
           

4.captalize()、swapcase()、title():隻針對單詞

  • catalize():字元串的首字母大寫
  • swapcase():大小寫互換
  • title():标簽,所有單詞的首字母大寫
# str之captalize()、swapcase()、title()
name = 'nick handsome sWAPCASE'

print(f"name.capitalize(): {name.capitalize()}")
print(f"name.swapcase(): {name.swapcase()}")  # 大小寫互轉
print(f"name.title(): {name.title()}")
name.capitalize(): Nick handsome swapcase
name.swapcase(): NICK HANDSOME Swapcase
name.title(): Nick Handsome Swapcase
           

5.is數字系列(隻是為了告訴你,判斷是否為數字時除了中文數字以後使用isdigit()即可)

  • isdecimal(): 檢查字元串是否值包含十進制字元,如果是傳回True,否則傳回False。
  • isdigit(): 如果字元串隻包含數字則傳回True,否則傳回False。
  • isnumeric(): 如果字元串中隻包含數字字元,則傳回True,否則傳回False。
num = "1"  #unicode
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = "1" # 全角
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = b"1" # byte
num.isdigit()   # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'

num = "IV" # 羅馬數字
num.isdigit()   # True
num.isdecimal() # False
num.isnumeric() # True

num = "四" # 漢字
num.isdigit()   # False
num.isdecimal() # False
num.isnumeric() # True

===================
isdigit()
True: Unicode數字,byte數字(單位元組),全角數字(雙位元組),羅馬數字
False: 漢字數字
Error: 無

isdecimal()
True: Unicode數字,全角數字(雙位元組)
False: 羅馬數字,漢字數字
Error: byte數字(單位元組)

isnumeric()
True: Unicode數字,全角數字(雙位元組),羅馬數字,漢字數字
False: 無
Error: byte數字(單位元組)

================
import unicodedata

unicodedata.digit("2")   # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0

unicodedata.digit("2")   # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0

unicodedata.digit(b"3")   # TypeError: must be str, not bytes
unicodedata.decimal(b"3") # TypeError: must be str, not bytes
unicodedata.numeric(b"3") # TypeError: must be str, not bytes

unicodedata.digit("Ⅷ")   # ValueError: not a digit
unicodedata.decimal("Ⅷ") # ValueError: not a decimal
unicodedata.numeric("Ⅷ") # 8.0

unicodedata.digit("四")   # ValueError: not a digit
unicodedata.decimal("四") # ValueError: not a decimal
unicodedata.numeric("四") # 4.0

#"〇","零","一","壱","二","弐","三","參","四","五","六","七","八","九","十","廿","卅","卌","百","千","萬","萬","億"
           

6.is其他

  • isalnum(): 如果字元串至少有一個字元并且所有字元都是字母或數字則傳回True,否則傳回False。
  • isalpha(): 如果字元串至少有一個字元并且所有字元都是字母則傳回True,否則傳回False。
  • islower(): 如果字元串中隻包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是小寫,則傳回True,否則傳回False。
  • isspace(): 如果字元串中隻包含空白,則傳回True,否則傳回False
  • isupper(): 如果字元串中包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是大寫,則傳回True,否則傳回False。
  • istitle(): 如果字元串是标題類型的(見title()),則傳回True,否則傳回False。

4.存一個值or多個值:一個值

5.有序or無序:隻要是有索引的,都是有序的,是以字元串是有序的。

name = 'nick'
print(f'first:{id(name)}')
name = 'nick handsome'
print(f'second:{id(name)}')
first:4377100160
second:4377841264
           

6.可變or不可變:不可變資料類型

轉載于:https://www.cnblogs.com/SkyOceanchen/p/11270441.html