1. 程式人生 > 實用技巧 >python基礎-字串型別

python基礎-字串型別

# 1、作用
# 2、定義
# 定義:在單引號\雙引號\三引號內包含一串字元
name1 = 'jason'  # 本質:name = str('任意形式內容')
name2 = "lili"  # 本質:name = str("任意形式內容")
name3 = """ricky"""  # 本質:name = str("""任意形式內容""")
# msg='hello' # msg=str('msg')
# print(type(msg))

# 3、型別轉換
# str可以把任意其他型別都轉成字串
# res=str({'a':1})
# print(res,type(res))
>>> type(str([1,2,3])) # list->str
<class 'str'>
>>> type(str({"name":"jason","age":18})) # dict->str
<class 'str'>
>>> type(str((1,2,3)))  # tuple->str
<class 'str'>
>>> type(str({1,2,3,4})) # set->str
<class 'str'>
# 4、使用:內建方法
# 4.1 優先掌握
# 4.1.1、按索引取值(正向取+反向取) :只能取
msg='hello world'
# 正向取
# print(msg[0])
# print(msg[5])
# 反向取
# print(msg[-1])

# 只能取
# msg[0]='H'


# 4.1.2、切片:索引的拓展應用,從一個大字串中拷貝出一個子字串
msg='hello world'
# 顧頭不顧尾
# res=msg[0:5] #x
# print(res)
# print(msg)

# 步長
# res=msg[0:5:2] # 0 2 4
# print(res) # hlo
# 反向步長(瞭解) # res=msg[5:0:-1] # print(res) #" olle" msg='hello world' # res=msg[:] # res=msg[0:11] # print(res) # res=msg[::-1] # 把字串倒過來 # print(res) # 4.1.3、長度len # msg='hello world' # print(len(msg)) # 4.1.4、成員運算in和not in # 判斷一個子字串是否存在於一個大字串中 # print("alex" in "alex is sb") # print("alex" not in "alex is sb")
# print(not "alex" in "alex is sb") # 不推薦使用 # 4.1.5、移除字串左右兩側的符號strip # 預設去掉的空格 # msg=' egon ' # res=msg.strip() # print(msg) # 不會改變原值 # print(res) # 是產生了新值 # 預設去掉的空格 # msg='****egon****' # print(msg.strip('*')) # 瞭解:strip只取兩邊,不去中間 # msg='****e*****gon****' # print(msg.strip('*')) # msg='**/*=-**egon**-=()**' # print(msg.strip('*/-=()')) # 應用 # inp_user=input('your name>>: ').strip() # inp_user=" egon" # inp_pwd=input('your password>>: ').strip() # if inp_user == 'egon' and inp_pwd == '123': # print('登入成功') # else: # print('賬號密碼錯誤') # 4.1.6、切分split:把一個字串按照某種分隔符進行切分,得到一個列表 # # 預設分隔符是空格 # info='egon 18 male' # res=info.split() # print(res) # # 指定分隔符 # info='egon:18:male' # res=info.split(':') # print(res) # 指定分隔次數(瞭解) # info='egon:18:male' # res=info.split(':',1) # print(res) # 4.1.7、迴圈 # info='egon:18:male' # for x in info: # print(x) # 4.2 需要掌握 #4.2.1、strip,lstrip,rstrip # msg='***egon****' # print(msg.strip('*')) # print(msg.lstrip('*')) # print(msg.rstrip('*')) #4.2.2、lower,upper # msg='AbbbCCCC' # print(msg.lower()) # print(msg.upper()) #4.2.3、startswith,endswith # print("alex is sb".startswith("alex")) # print("alex is sb".endswith('sb')) #4.2.4、format #4.2.5、split,rsplit:將字串切成列表 # info="egon:18:male" # print(info.split(':',1)) # ["egon","18:male"] # print(info.rsplit(':',1)) # ["egon:18","male"] #4.2.6、join: 把列表拼接成字串 # l=['egon', '18', 'male'] # res=l[0]+":"+l[1]+":"+l[2] # res=":".join(l) # 按照某個分隔符號,把元素全為字串的列表拼接成一個大字串 # print(res) # l=[1,"2",'aaa'] # ":".join(l) #4.2.7、replace # msg="you can you up no can no bb" # print(msg.replace("you","YOU",)) # print(msg.replace("you","YOU",1)) #4.2.8、isdigit # 判斷字串是否由純數字組成 # print('123'.isdigit()) # print('12.3'.isdigit()) # age=input('請輸入你的年齡:').strip() # if age.isdigit(): # age=int(age) # int("abbab") # if age > 18: # print('猜大了') # elif age < 18: # print('猜小了') # else: # print('才最了') # else: # print('必須輸入數字,傻子') # 4.3瞭解 #4.3.1、find,rfind,index,rindex,count msg='hello egon hahaha' # 找到返回起始索引 # print(msg.find('e')) # 返回要查詢的字串在大字串中的起始索引 # print(msg.find('egon')) # print(msg.index('e')) # print(msg.index('egon')) # 找不到 # print(msg.find('xxx')) # 返回-1,代表找不到 # print(msg.index('xxx')) # 丟擲異常 # msg='hello egon hahaha egon、 egon' # print(msg.count('egon')) #4.3.2、center,ljust,rjust,zfill # print('egon'.center(50,'*')) # print('egon'.ljust(50,'*')) # print('egon'.rjust(50,'*')) # print('egon'.zfill(10)) #4.3.3、expandtabs # msg='hello\tworld' # print(msg.expandtabs(2)) # 設定製表符代表的空格數為2 #4.3.4、captalize,swapcase,title # print("hello world egon".capitalize()) # print("Hello WorLd EGon".swapcase()) # print("hello world egon".title()) #4.3.5、is數字系列 #4.3.6、is其他 # print('abc'.islower()) # print('ABC'.isupper()) # print('Hello World'.istitle()) # print('123123aadsf'.isalnum()) # 字串由字母或數字組成結果為True # print('ad'.isalpha()) # 字串由由字母組成結果為True # print(' '.isspace()) # 字串由空格組成結果為True # print('print'.isidentifier()) # print('age_of_egon'.isidentifier()) # print('1age_of_egon'.isidentifier()) num1=b'4' #bytes num2=u'4' #unicode,python3中無需加u就是unicode num3='' #中文數字 num4='' #羅馬數字 # isdigit只能識別:num1、num2 # print(num1.isdigit()) # True # print(num2.isdigit()) # True # print(num3.isdigit()) # False # print(num4.isdigit()) # False # isnumberic可以識別:num2、num3、num4 # print(num2.isnumeric()) # True # print(num3.isnumeric()) # True # print(num4.isnumeric()) # True # isdecimal只能識別:num2 print(num2.isdecimal()) # True print(num3.isdecimal()) # False print(num4.isdecimal()) # False
# 1.find,rfind,index,rindex,count
# 1.1 find:從指定範圍內查詢子字串的起始索引,找得到則返回數字1,找不到則返回-1
>>> msg='tony say hello'
>>> msg.find('o',1,3)  # 在索引為1和2(顧頭不顧尾)的字元中查詢字元o的索引
1  
# 1.2 index:同find,但在找不到時會報錯
>>> msg.index('e',2,4) # 報錯ValueError
# 1.3 rfind與rindex:略
# 1.4 count:統計字串在大字串中出現的次數
>>> msg = "hello everyone"
>>> msg.count('e')  # 統計字串e出現的次數
4
>>> msg.count('e',1,6)  # 字串e在索引1~5範圍內出現的次數
1

# 2.center,ljust,rjust,zfill
>>> name='tony'
>>> name.center(30,'-')  # 總寬度為30,字串居中顯示,不夠用-填充
-------------tony-------------
>>> name.ljust(30,'*')  # 總寬度為30,字串左對齊顯示,不夠用*填充
tony**************************
>>> name.rjust(30,'*')  # 總寬度為30,字串右對齊顯示,不夠用*填充
**************************tony
>>> name.zfill(50)  # 總寬度為50,字串右對齊顯示,不夠用0填充
0000000000000000000000000000000000000000000000tony

# 3.expandtabs
>>> name = 'tony\thello'  # \t表示製表符(tab鍵)
>>> name
tony    hello
>>> name.expandtabs(1)  # 修改\t製表符代表的空格數
tony hello

# 4.captalize,swapcase,title
# 4.1 captalize:首字母大寫
>>> message = 'hello everyone nice to meet you!'
>>> message.capitalize()
Hello everyone nice to meet you!  
# 4.2 swapcase:大小寫翻轉
>>> message1 = 'Hi girl, I want make friends with you!'
>>> message1.swapcase()  
hI GIRL, i WANT MAKE FRIENDS WITH YOU!  
#4.3 title:每個單詞的首字母大寫
>>> msg = 'dear my friend i miss you very much'
>>> msg.title()
Dear My Friend I Miss You Very Much 

# 5.is數字系列
#在python3中
num1 = b'4' #bytes
num2 = u'4' #unicode,python3中無需加u就是unicode
num3 = '' #中文數字
num4 = '' #羅馬數字

#isdigt:bytes,unicode
>>> num1.isdigit()
True
>>> num2.isdigit()
True
>>> num3.isdigit()
False
>>> num4.isdigit() 
False

#isdecimal:uncicode(bytes型別無isdecimal方法)
>>> num2.isdecimal() 
True
>>> num3.isdecimal() 
False
>>> num4.isdecimal() 
False

#isnumberic:unicode,中文數字,羅馬數字(bytes型別無isnumberic方法)
>>> num2.isnumeric() 
True
>>> num3.isnumeric() 
True
>>> num4.isnumeric() 
True

# 三者不能判斷浮點數
>>> num5 = '4.3'
>>> num5.isdigit()
False
>>> num5.isdecimal()
False
>>> num5.isnumeric()
False

'''
總結:
    最常用的是isdigit,可以判斷bytes和unicode型別,這也是最常見的數字應用場景
    如果要判斷中文數字或羅馬數字,則需要用到isnumeric。
'''

# 6.is其他
>>> name = 'tony123'
>>> name.isalnum() #字串中既可以包含數字也可以包含字母
True
>>> name.isalpha() #字串中只包含字母
False
>>> name.isidentifier()
True
>>> name.islower()  # 字串是否是純小寫
True
>>> name.isupper()  # 字串是否是純大寫
False
>>> name.isspace()  # 字串是否全是空格
False
>>> name.istitle()  # 字串中的單詞首字母是否都是大寫
False