一、字符串格式化-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不会
五、