一、字符串格式化-format()
通過位置:
>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'
>>> "{0} {1}".format("hello", "world") # 設置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
通過關鍵詞:(可在format中引用變量)
site = {"name": "百度", "url": "www.baidu.com"} # 字典
>>>"網站:{name}, 地址:{url}".format(**site)
"網站:百度, 地址:www.baidu.com"
site=["百度","www.baidu.com"] #
>>>"網站:{name}, 地址:{url}".format(name=site[0],url=site[1])
"網站:百度, 地址:www.baidu.com"
通過下標:
my_list = ['百度', 'www.baidu.com']
>>>"網站:{0[0]}, 地址:{0[1]}".format(my_list)) # "0" 是必須的
網站:百度, 地址:www.baidu.com
備注:如果字符串中需要展示{}是,兩個{{ }}用作轉譯
二、檢查字符串類型
s為字符串
s.isalnum() 所有字符都是數字或者字母
s.isalpha() 所有字符都是字母
s.isdigit() 所有字符都是數字
s.islower() 所有字符都是小寫
s.isupper() 所有字符都是大寫
s.istitle() 所有單詞都是首字母大寫,像標題
s.isspace() 所有字符都是空白字符、\t、\n、\r
通用判斷元素類型
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元組中的一個返回 True
True
三、檢查字符串是否以指定子字符串開頭或結尾
startswith() 方法用於檢查字符串是否是以指定子字符串開頭(PS:只看開頭)
str = "this is string example....wow!!!"
>>>str.startswith( 'this' ) True
>>>str.startswith( 'is', 2, 4 ) True
>>>str.startswith( 'this', 2, 4 ) False
endswith() 方法用於判斷字符串是否以指定后綴結尾(PS:只看后綴)
suffix = "wow!!!"
>>>str.endswith(suffix) True
>>>str.endswith(suffix,20) True
suffix = "is"
>>>str.endswith(suffix, 2, 4) True
>>>str.endswith(suffix, 2, 6) False
備注:空格算字符;(str,start,end)star和end概念同range
四、字符串首次出現的位置
find()、index()
用法相同,找到元素在字符串中首次出現的位置,index找不到時報錯而find不會
五、