格式化字符串的输出
最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
我叫 小明 今年 10 岁!
>>> name = 'Runoob'
>>> 'Hello %s' % name
'Hello Runoob'
python字符串格式化符号
Python2.6 开始,新增了一种格式化字符串的函数 str.format()
,它增强了字符串格式化的功能
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
设置参数
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
格式化数字的多种方法:
>>> print("{:.2f}".format(3.1415926))
3.14
f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法
>>> name = 'Runoob'
>>> f'Hello {name}' # 替换变量
'Hello Runoob'
>>> f'{1+2}' # 使用表达式
'3'
>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'
Python 的字符串常用内建函数如下:
str.count(sub, start= 0,end=len(string))
- sub – 搜索的子字符串
- start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
- end --字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
- 该方法返回子字符串在字符串中出现的次数
sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
#str.count('run', 0, 10) : 1
str.find(str, beg=0, end=len(string))
- str – 指定检索的字符串
- beg – 开始索引,默认为0。
- end – 结束索引,默认为字符串的长度。
- 如果包含子字符串返回开始的索引值,否则返回-1。
>>>info = 'abca'
>>> print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
0
>>> print(info.find('a', 1)) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
3
>>> print(info.find('3')) # 查找不到返回-1
-1
str.join(sequence)
- sequence – 要连接的元素序列。
- 返回通过指定字符连接序列中元素后生成的新字符串。
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq )) #result:r-u-n-o-o-b
print (s2.join( seq )) #result:runoob
str.split(str="", num=string.count(str))
- str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
- num – 分割次数。默认为 -1, 即分隔所有。
- 返回分割后的字符串列表。
>>>str = "this is string example....wow!!!"
>>>print (str.split( )) # 以空格为分隔符
['this', 'is', 'string', 'example....wow!!!']
>>>print (str.split('i',1)) # 以 i 为分隔符
['th', 's is string example....wow!!!']
>>>print (str.split('w')) # 以 w 为分隔符
['this is string example....', 'o', '!!!']
以上是部分字符串内建函数
摘抄:https://www.runoob.com/python3/python3-string.html