1、string簡介:
string就是字元串,字元串是Python中最長用的數據類型,可以使用引號('或")來創建字元串。事實上,在Python中,加了引號的字元都被認爲是字元串。
name = "Changsh" #雙引號
age ="5000" #只要加雙引號就是字元串
age_1 =5000 #不加,整形
msg ="""I'm in Changsha"""#三雙引號
msg_1 ='''I' m in Hengyang'''#三單引號
hometowm ='Changsha' #單引號
print(type(name),type(age),type(age_1),type(msg),type(msg_1),type(hometown),sep="|")
2、字元串運算及操作:
拼接:
>>> a="Hello"
>>> b="Python"
>>> a+b
'HelloPython'
注意,字元串的拼接只能是對方都是字元串,不能跟數字或其它類型拼接。
>>>age_1=5000
>>>name+age_1
Traceback (most recent call last):
File"<stdin>",line 1,in <module>
TypeError:must be str,not int
重複:
>>> a="Hello"
>>> a*3
'HelloHelloHello'
字元串索引:
#########0123456789012345367890123456789
>>> a = "Life is short,I use python"
>>>len(a)
27
>>> #索引
>>>a[0]
'L'
>>>a[-1]
'n'
>>> #切片
...
>>> a[:13] #從第一個元素開始,一直到索引值爲12的元素
'Life is short'
>>> a[15:] #從索引值爲15的元素開始,一直到最後
'I use python'
>>> a[15::2] #從索引值爲15的元素開始,步長爲2,即每次跳過一個元素,一直到最後
'Iuepto'
>>> a[::-1] #逆序輸出
'nohtyp esu I ,trohs si efiL'
大小寫轉換:
str.lower():轉小寫
str.upper():轉大寫
str.swapcase():大小寫對換
str.capitalize():字元串首爲大寫,其餘小寫
str.title():以分隔符爲標記,首字元爲大寫,其餘爲小寫
>>> a="Life is short, I use python"
>>> a.lower() #將所有大寫字元轉換爲小寫字元
'life is short, i use python'
>>> a.upper() #將所有小寫字元轉換爲大寫字元
'LIFE IS SHORT, I USE PYTHON'
>>> a.swapcase() #將大小寫互換
'lIFE IS SHORT, i USE PYTHON'
>>> a.capitalize() #將首字元大寫
'Life is short, i use python'
>>> a.title() #返回標題化的字元串
'Life Is Short, I Use Python'
>>>
字元串格式輸出對齊:
str.center()居中
str.ljust()左居中
str.rjust()右居中
str.zfill()左居中,以0填充長度
刪除指定參數:
str.lstrip()
str.rstrip()
str.strip()
計數:
Excel表格中:
=COUNTIF(B2:B31,">=30")/COUNT(B2:B31)
字元串條件判斷:
isalnum(),字元串由字母或數字組成,
isalpha(),字元串只由字母組成,
isdigit(),字元串只由數字組成