基本資料型別——字串型別str
1、定義
name = 'Tony'
address = ''上海市浦東新區''
sex = '''男
喜歡面條'''
用單引號、雙引號、多引號,都可以定義字串,本質上是沒有區別的,不過需要注意:
#1、需要考慮引號嵌套的配對問題
msg = "My name is Tony , I'm 18 years old!"
#內層有單引號,外層就需要用雙引號
#2、多引號可以寫多行字串
msg = '''
天下只有兩種人,
比如一串葡萄到手,一種人挑最好的先吃,另一種人把最好的留到最后吃,
照例第一種人應該樂觀,因為他每吃一顆都是吃剩的葡萄里最好的;
第二種人應該悲觀,因為他每吃一顆都是吃剩的葡萄里最壞的,
不過事實卻適得其反,緣故是第二種人還有希望,第一種人只有回憶,
'''
2、作用
用來記錄人的名字,家庭住址,性別等描述性質的狀態
3、型別轉換
# str可以把任意其他型別都轉成字串
>>>
>>> res=str({'a':1})
>>> print(res,type(res))
{'a': 1} <class 'str'>
>>>
4、使用:
4.1 數學運算
數字可以進行加減乘除等運算,字串呢?也可以,但只能進行"相加"和"相乘"運算, >>> name = 'tony' >>> age = '18' >>> name + age #相加其實就是簡單的字串拼接 'tony18' >>> name * 5 #相乘就相當于將字串相加了5次 'tonytonytonytonytony'
4.2 內置方法
4.2.1、按索引取值——(正向取+反向取) :只能取
>>> msg='hello world'
>>> #正向取
>>> print(msg[0])
h
>>> print(msg[5])
>>> #反向取
>>> print(msg[-1])
d
>>> #只能取,不能改寫
>>> msg[0]='H'
Traceback (most recent call last):
File "<pyshell#86>", line 1, in <module>
msg[0]='H'
TypeError: 'str' object does not support item assignment
>>>
4.2.2、切片——索引的拓展應用,從一個大字串中拷貝出一個子字串
>>> # 顧頭不顧尾 # [x:y],--指的是 [x,y)左閉右開的區間 # x--開始的索引號,
# y--在索引號[y-1]結束,取到索引號[y-1] 所指的字符就結束
[0:5],意為 從第一個索引[0]所指的字符開始,取到索引[4],即5個字符
>>>
>>> msg='hello world'
>>> res=msg[0:5]
>>> print(res)
hello
>>> print(msg)
hello world
>>>
>>> #步長
# 依次讀取索引 0 2 4 所對應的字符
# [x:y:z],
# x--開始的索引號,
# y--在索引號[y-1]結束,即取到索引號[y-1] 所指的字符就結束,
# z--間隔的索引個數,即從索引[x]開始,每隔z個間隔,依次讀取,直到索引號[y-1]結束
[0:5:2],意為 從第一個索引[0]所指的字符開始,每隔2個間隔,讀取一個字符,直到取到索引[4],即3個字符
>>> res=msg[0:5:2]
>>> print(res)
hlo
>>>
>>> #反向步長(了解)
>>> msg='hello world'
>>> res=msg[5:0:-1]
>>> print(res)
olle
>>>
>>> msg='hello world'
>>> res=msg[:] # [:]不輸入,默認為 res=msg[0:11]
>>> print(res)
hello world
>>> res=msg[::-1] # 把字串倒過來讀取
>>> print(res)
dlrow olleh
>>>
4.2.3、長度 len()
>>>
>>> msg='hello world'
>>> print(len(msg))
11
>>>
4.2.4、成員運算in和not in
>>>
>>> #判斷一個子字串是否存在于一個大字串中
>>> print("alex" in "alex is sb")
True
>>> print("alex" not in "alex is sb")
False
>>> print(not "alex" in "alex is sb") # 不推薦使用,語法沒錯,只是不符合一般邏輯思維習慣
False
>>>
4.2.5、移除字串左右兩側的符號strip(‘字符’)
#注意,字符要用引號括起來
>>>
>>> # 默認去掉的空格
>>> msg=' egon '
>>> res=msg.strip()
>>> print(msg) # 不會改變原值
egon
>>> print(res) # 去除了空格,是產生了新值
egon
>>>
>>> #去掉其他符號
>>> msg='*******egon****'
>>> print(msg.strip('*'))
egon
>>> msg='@@@egon@@*'
>>> print(msg.strip('*'))
@@@egon@@
>>> print(msg.strip('*@'))
egon
>>>
>>> msg='@@@egon@ @ *'
>>> print(msg.strip('*@ '))
egon
>>>
>>> # 了解:strip只去除兩邊,不去中間
>>> msg='*******eg*****on****'
>>> print(msg.strip('*'))
eg*****on
>>> msg='**/*=-**egon**-=()**'
>>> print(msg.strip('*/-=()'))
egon
>>>
>>> # 應用_自動清除用戶手抖輸入的多余空格 >>> in_name= input('please input your name:').strip() please input yuor name:' cc' # 為何failed login,原因是這里輸入的結果為字串 ' cc',而不是 字串 cc,后面的條件判斷是字串 cc >>> in_code= input('please input your code:').strip() please input yuor code:' 123' # 為何failed login,原因是這里輸入的結果為字串 ' 123',而不是 字串 123,后面的條件判斷是字串 123 >>> if in_name == 'cc'and in_code == '123': print('login successfully') else: print('failed login')
failed login
>>> in_name= input('please input yuor name:').strip()
please input yuor name:cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code:123
>>> if in_name == 'cc' and in_code == '123':
print('login successfully')
else:
print('failed login')
login successfully
——————————————————————————
>>> in_name= input('please input yuor name:').strip() please input yuor name:cc >>> in_code= input('please input yuor code:').strip() please input yuor code: 123 #末尾有輸入一個空格 >>> if in_name == 'cc'and in_code == '123': print('login successfully') else: print('failed login')
login successfully ———————————————————————————
>>> in_name= input('please input yuor name:').strip()
please input yuor name:'cc' # 為何failed login,原因是這里輸入的結果為字串 ' cc',而不是 字串 cc,后面的條件判斷是字串 cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code:123
>>>
>>> if in_name == 'cc'and in_code == '123':
print('login successfully')
else:
print('failed login')
failed login
—————————————————————————————
>>> in_name= input('please input yuor name:').strip()
please input yuor name:cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code:123
>>> if in_name == 'cc' and in_code == 123: #將123的引號去掉,則為整型,但是用戶輸入的是字串型別,所以后面判斷結果為假
print('login successfully')
else:
print('failed login')
failed login
——————————
>>> in_name= input('please input yuor name:').strip()
please input yuor name:cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code:123 >>> in_code=int(in_code) #用戶輸入的密碼,是字串型別,將其強制轉換為整型,再進行條件判斷,則結果為真 >>> if in_name == 'cc'and in_code == 123:
print('login successfully')
else:
print('failed login')
login successfully
>>>
4.2.6、切分split:把一個字串按照某種分隔符進行切分,得到一個串列 # # 默認分隔符是空格
>>> # 默認分隔符是空格
>>> info='cat love mili'
>>> res=info.split()
>>> print(res)
['cat', 'love', 'mili']
>>> # 指定分隔符
>>> info='cat:love:mili'
>>> res=info.split(':')
>>> print(res)
['cat', 'love', 'mili']
>>> # 指定分隔次數(了解)
>>> info='cat:love:mili'
>>> res=info.split(':',1)
>>> print(res)
['cat', 'love:mili']
>>>
4.2.7、回圈
>>> 回圈輸出,即一直回圈輸出,逐字輸出,直到輸出完畢
>>> info='cat love mili'
>>> for x in info:
print(x)
c
a
t
l
o
v
e
m
i
l
i
>>>
4.3 需要掌握的其他應用
4.3.1、strip,lstrip,rstrip
>>> msg='*******egon****'
>>> print(msg.strip('*'))
egon
>>> print(msg.lstrip('*')) #去除left左側
egon****
>>> print(msg.rstrip('*')) #去除right右側
*******egon
4.3.2、lower,upper
>>>
>>> msg='AAAAAegondddASSss'
>>> print(msg.lower()) #全部轉換成小寫
aaaaaegondddassss
>>> print(msg.upper())#全部轉換成大寫
AAAAAEGONDDDASSSS
>>>
4.3.3、startswith,endswith——判斷字串的開頭或結尾的子字符
>>>
>>> print('cat love mili'.startswith('cat'))
True
>>> print('cat love mili'.startswith('mili'))
False
>>> print('cat love mili'.endswith('mili'))
True
>>> print('cat love mili'.endswith('cat'))
False
>>>
4.3.4、format——賦值
>>> #逐一將format后面的值賦給{}
>>> res='{} {} {}'.format('cc','18','mili')
>>> print(res)
cc 18 mili
>>> #按照 format后面的值的索引,賦值給對應索引號的{}
>>> res='{1} {0} {1}'.format('cc','18','mili')
>>> print(res)
18 cc 18
>>> res='{0} {2} {1}'.format('cc','18','mili')
>>> print(res)
cc mili 18
>>> #按照 format后面的變數名稱,賦值給對應變數名稱的{}
>>> res='{name} {age} {lover}'.format(lover='mili',name='cc',age='18')
>>> print(res)
cc 18 mili
>>>
4.3.5、split,rsplit:將字串切成串列
>>> info='cat:love:mili'
>>> print(info.split(':',1))
['cat', 'love:mili']
>>> print(info.rsplit(':',1))#從右側開始切片
['cat:love', 'mili']
>>>
4.3.6、join: 把串列拼接成字串
>>>連接字串的三種方式:
>>> l=['cat','love','mili']
>>> res=l[0]+":"+l[1]+":"+l[2]
>>> print(res)
cat:love:mili
>>> res=':'.join(l)# 按照某個分隔符號,把元素全為字串的串列拼接成一個大字串
>>> print(res)
cat:love:mili
>>> ':'.join(l)
'cat:love:mili'
>>>
4.3.7、replace
>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC')) #未指定個數,默認將全部'cat'替換為'CC'
CC love mili love CC
>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',)) #未輸入替換個數,默認將全部'cat'替換為'CC'
CC love mili love CC
>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',1)) #輸入替換個數為1,將第一個'cat'替換為'CC'
CC love mili love cat
>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',2)) #輸入替換個數為‘cat’的總數,將全部'cat'替換為'CC'
CC love mili love CC
>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',3)) #輸入替換個數超過‘cat’的總數,將全部'cat'替換為'CC'
CC love mili love CC
4.3.8、isdigit
>>>
>>> # 判斷字串是否由純數字組成
>>> print('123'.isdigit())
True
>>> print('12.3'.isdigit())
False
>>>
>>>
>>> age=input('請輸入你的年齡:').strip()
請輸入你的年齡:19
>>> if age.isdigit():
age=int(age)
if age > 18:
print('猜大了')
elif age < 18:
print('猜小了')
else:
print('猜對了')
else:
print('請輸入數字')
猜大了
>>>
4.4 其他應用的了解
4.4.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.4.2、center,ljust,rjust,zfill
# print('egon'.center(50,'*'))
# print('egon'.ljust(50,'*'))
# print('egon'.rjust(50,'*'))
# print('egon'.zfill(10))
4.4.3、expandtabs
# msg='hello\tworld'
# print(msg.expandtabs(2)) # 設定制表符代表的空格數為2
4.4.4、captalize,swapcase,title
# print("hello world egon".capitalize())
# print("Hello WorLd EGon".swapcase())
# print("hello world egon".title())
4.4.5、is數字系列
4.4.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
5、格式化字串的四種方法
https://zhuanlan.zhihu.com/p/110406030
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/181832.html
標籤:Python
上一篇:Python類和實體【新手必學】
