python基礎資料型別 (Elementary Data Type)——str

來源:互聯網
上載者:User

標籤:程式   字母   功能   找不到   form   type   指定   really   for迴圈   

一、字串的建立
test = str() / ""test = str("licheng") / "licheng"
  • 無參數,建立Null 字元串
  • 一個參數,建立一般字元串
  • 兩個參數,int(位元組,編碼)
二、字串的常用方法
#capitalize():字串首字元大寫string = ‘this is a string.‘new_str = string.capitalize()print(new_str)#輸出:This is a string. #center(width, fillchar=None):將字串放在中間,在指定長度下,首尾以指定輸入鍵台string = ‘this is a string.‘new_str = string.center(30,‘*‘)print(new_str)#輸出:******this is a string.******* #count(sub, start=None, end=None):計算字串中某字元的數量string = ‘this is a string.‘new_str = string.count(‘i‘)print(new_str)#輸出:3 #decode/encode(encoding=None, errors=None):解碼/解碼string = ‘this is a string.‘new_str = string.decode()new_str = string.encode()print(new_str) #endswith(self, suffix, start=None, end=None):判斷是否以某字元結尾string = ‘this is a string.‘new_str = string.endswith(‘ing.‘)print(new_str)#輸出:True #find(self, sub, start=None, end=None):在字串中尋找指定字元的位置string = ‘this is a string.‘new_str = string.find(‘a‘) #找的到的情況print(new_str)#輸出:8new_str = string.find(‘xx‘) #找不到的情況返回-1print(new_str)#輸出:-1 #index(self, sub, start=None, end=None):;類似findstring = ‘this is a string.‘new_str = string.index(‘a‘) #找的到的情況print(new_str)#輸出:8new_str = string.index(‘xx‘) #找不到的情況,程式報錯print(new_str)#輸出:程式運行報錯,ValueError: substring not found #isalnum(self):判斷字串中是否都是數字和字母,如果是則返回True,否則返回Falsestring = ‘My name is yue,my age is 18.‘new_str = string.isalnum()print(new_str)#輸出:Falsestring = ‘haha18121314lala‘new_str = string.isalnum()print(new_str)#輸出:True #isalpha(self):判斷字串中是否都是字母,如果是則返回True,否則返回Falsestring = ‘abcdefg‘new_str = string.isalpha()print(new_str)#輸出:Truestring = ‘my name is yue‘new_str = string.isalpha() #字母中間帶空格、特殊字元都不行print(new_str)#輸出:False # isdigit(self):判斷字串中是否都是數字,如果是則返回True,否則返回Falsestring = ‘1234567890‘new_str = string.isdigit()print(new_str)#輸出:Truestring = ‘haha123lala‘new_str = string.isdigit() #中間帶空格、特殊字元都不行print(new_str)#輸出:False # islower(self):判斷字串中的字母是否都是小寫,如果是則返回True,否則返回Falsestring = ‘my name is yue,my age is 18.‘new_str = string.islower()print(new_str)#輸出:Truestring = ‘My name is Yue,my age is 18.‘new_str = string.islower()print(new_str)#輸出:False # isupper(self):檢測字串中所有的字母是否都為大寫。string = ‘MY NAME IS YUE.‘new_str = string.isupper()print(new_str)#輸出:Truestring = ‘My name is Yue.‘new_str = string.isupper()print(new_str)#輸出:False # join(self, iterable):將序列中的元素以指定的字元串連產生一個新的字串。string = ("haha","lala","ohoh")str = "-"print(str.join(string))#輸出:haha-lala-ohoh # lower(self):轉換字串中所有大寫字元為小寫。string = "My Name is YUE."print(string.lower())# 輸出:my name is yue. # lstrip(self, chars=None):截掉字串左邊的空格或指定字元。string = " My Name is YUE."print(string.lstrip())#輸出:My Name is YUE.string = "My Name is YUE."print(string.lstrip(‘My‘))#輸出: Name is YUE. #replace(self, old, new, count=None):把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個參數max,則替換不超過 max 次。string = "My name is yue."print(string.replace("yue","ying"))#輸出:My name is ying. # rfind(self, sub, start=None, end=None):返回字串最後一次出現的位置,如果沒有匹配項則返回-1。string = "My name is yue."print(string.rfind(‘is‘))#輸出:8string = "My name is yue."print(string.rfind(‘XXX‘))#輸出:-1 # split(self, sep=None, maxsplit=None):通過指定分隔字元對字串進行切片。string = "haha lala gege"print(string.split(‘ ‘))#輸出:[‘haha‘, ‘lala‘, ‘gege‘]print(string.split(‘ ‘, 1 ))#輸出: [‘haha‘, ‘lala gege‘] # rsplit(self, sep=None, maxsplit=None):通過指定分隔字元對字串從右進行切片。string = "haha lala gege"print(string.rsplit(‘ ‘))#輸出:[‘haha‘, ‘lala‘, ‘gege‘]print(string.rsplit(‘ ‘, 1 ))#輸出: [‘haha lala‘, ‘gege‘] # rstrip(self, chars=None):刪除 string 字串末尾的指定字元(預設為空白格).string = " My name is yue. "print(string.rstrip())#輸出: My name is yue. # strip(self, chars=None):移除字串頭尾指定的字元(預設為空白格)。string = " My name is yue. "print(string.strip())#輸出:My name is yue. # upper(self):將字串中的小寫字母轉為大寫字母。string = "my name is yue,my age is 18."print(string.upper())#輸出:MY NAME IS YUE,MY AGE IS 18.
 str源碼三、字串的公用功能
  • 索引(只能取一個元素)
  • 切片(取多個元素)
  • 長度(len)
    • python2:按位元組算長度
    • python3:按字元算長度
  • for迴圈(同長度的版本迴圈單位)
四、字元與位元組的轉換
# 將gbk編碼的字元轉化為位元組s = "李程"b = bytes(s, encoding="gbk")type(b)  輸出為位元組類型# 將位元組轉化為字元c = str(b, encoding="gbk")
五、字串格式化

Python的字串格式化有兩種方式: 百分比符號方式、format方式

百分比符號的方式相對來說比較老,而format方式則是比較先進的方式,企圖替換古老的方式,目前兩者並存。

1、百分比符號方式

%[(name)][flags][width].[precision]typecode
 參數詳解

常用格式化:

tpl = "i am %s" % "spark" tpl = "i am %s age %d" % ("spark", 18) tpl = "i am %(name)s age %(age)d" % {"name": "spark", "age": 18} tpl = "percent %.2f" % 99.97623 tpl = "i am %(pp).2f" % {"pp": 123.425556, } tpl = "i am %.2f %%" % {"pp": 123.425556, }

2、Format方式

[[fill]align][sign][#][0][width][,][.precision][type]
 參數詳解

 常用格式化:

 1 tpl = "i am {}, age {}, {}".format("seven", 18, ‘alex‘) 2    3 tpl = "i am {}, age {}, {}".format(*["seven", 18, ‘alex‘]) 4    5 tpl = "i am {0}, age {1}, really {0}".format("seven", 18) 6    7 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) 8    9 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)10   11 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})12   13 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])14   15 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)16   17 tpl = "i am {:s}, age {:d}".format(*["seven", 18])18   19 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)20   21 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})22  23 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)24  25 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)26  27 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)28  29 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

更多格式化操作:https://docs.python.org/3/library/string.html

python基礎資料型別 (Elementary Data Type)——str

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.