python中find函数忽略大小写_python字符串(大小写、判断、查找、分割、拼接、裁剪、替换、格式化)...
一、通用操作
1、Python len()
方法返回对象(字符、列表、元组等)长度或项目个数。
语法
len()方法语法:
len( q )
参数
q -- 对象。
返回值
返回对象长度。
实例
以下实例展示了 len() 的使用方法:
>>>str = "runoob"
>>> len(str) # 字符串长度
6
>>> l = [1,2,3,4,5]
>>> len(l) # 列表元素个数
5
2、python 成员运算符 in 和 not in
Python成员运算符测试给定值是否为序列中的成员,例如字符串,列表或元组。 有两个成员运算符,如下所述 -
in 如果在指定的序列中找到一个变量的值,则返回true,否则返回false。
not in 如果在指定序列中找不到变量的值,则返回true,否则返回false。
in
如果在指定的序列中找到值返回 True,否则返回 False。
x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
not in
如果在指定的序列中没有找到值返回 True,否则返回 False。
x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
以下实例演示了Python所有成员运算符的操作:
#!/usr/bin/python3
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("1 - 变量 a 在给定的列表中 list 中")
else:
print ("1 - 变量 a 不在给定的列表中 list 中")
if ( b not in list ):
print ("2 - 变量 b 不在给定的列表中 list 中")
else:
print ("2 - 变量 b 在给定的列表中 list 中")
# 修改变量 a 的值
a = 2
if ( a in list ):
print ("3 - 变量 a 在给定的列表中 list 中")
else:
print ("3 - 变量 a 不在给定的列表中 list 中")
以上实例输出结果:
1 - 变量 a 不在给定的列表中 list 中
2 - 变量 b 不在给定的列表中 list 中
3 - 变量 a 在给定的列表中 list 中
3、Python身份运算符
身份运算符用于比较两个对象的存储单元
is
is 是判断两个标识符是不是引用自一个对象
x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not
is not 是判断两个标识符是不是引用自不同对象
x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。
注: id() 函数用于获取对象内存地址。
以下实例演示了Python所有身份运算符的操作:
#!/usr/bin/python3
a = 20
b = 20
if ( a is b ):
print ("1 - a 和 b 有相同的标识")
else:
print ("1 - a 和 b 没有相同的标识")
if ( id(a) == id(b) ):
print ("2 - a 和 b 有相同的标识")
else:
print ("2 - a 和 b 没有相同的标识")
# 修改变量 b 的值
b = 30
if ( a is b ):
print ("3 - a 和 b 有相同的标识")
else:
print ("3 - a 和 b 没有相同的标识")
if ( a is not b ):
print ("4 - a 和 b 没有相同的标识")
else:
print ("4 - a 和 b 有相同的标识")
以上实例输出结果:
1 - a 和 b 有相同的标识
2 - a 和 b 有相同的标识
3 - a 和 b 没有相同的标识
4 - a 和 b 没有相同的标识
is 与 == 区别:
is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。
>>>a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True
4、Python运算符优先级
以下表格列出了从最高到最低优先级的所有运算符:
运算符
描述
**
指数 (最高优先级)
~ + -
按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % //
乘,除,求余数和取整除
+ -
加法减法
>> <<
右移,左移运算符
&
位 'AND'
^ |
位运算符
<= < > >=
比较运算符
== !=
等于运算符
= %= /= //= -= += *= **=
赋值运算符
is is not
身份运算符
in not in
成员运算符
not and or
逻辑运算符
以下实例演示了Python所有运算符优先级的操作:
#!/usr/bin/python3
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("(a + b) * c / d 运算结果为:", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("((a + b) * c) / d 运算结果为:", e)
e = (a + b) * (c / d); # (30) * (15/5)
print ("(a + b) * (c / d) 运算结果为:", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("a + (b * c) / d 运算结果为:", e)
以上实例输出结果:
(a + b) * c / d 运算结果为: 90.0
((a + b) * c) / d 运算结果为: 90.0
(a + b) * (c / d) 运算结果为: 90.0
a + (b * c) / d 运算结果为: 50.0
and 拥有更高优先级:
x = True
y = False
z = False
if x or y and z:
print("yes")
else:
print("no")
以上实例输出结果:
yes
注意:Pyhton3 已不支持 <> 运算符,可以使用 != 代替,如果你一定要使用这种比较运算符,可以使用以下的方式:
>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True
二、与大小写的相关方法
xgp = 'hello,wsd'
print(xgp)
# upper():将字符串转换为大写
xgp1 = xgp.upper()
print(xgp1)
# isupper():判断字符串是否都为大写
print(xgp1.isupper())
# lower():将字符串转换为小写
xgp2 = xgp1.lower()
print(xgp2)
# islower():判断字符串是否都为小写
print(xgp2.islower())
# title():将字符串中的单词转换为标题格式,每个单词首字母大写,其余小写
xgp3 = xgp2.title()
print(xgp3)
# istitle():判断字符事是不是一个标题
print(xgp3.istitle())
# swapcase():小写转大写,大写转小写
xgp4 = xgp3.swapcase()
print(xgp4)
xgp5 = xgp4.swapcase()
print(xgp5)
# capitalize():将首字母转换为大写
xgp6 = xgp5.capitalize()
print(xgp6)
以上实例输出结果:
# 原始输出
hello,wsd
# 将字符串转换为大写
HELLO,WSD
# 判断字符串是否都为大写
True
# 将字符串转换为小写
hello,wsd
# 判断字符串是否都为小写
True
# 将字符串中的单词转换为标题格式,每个单词首字母大写,其余小写
Hello,Wsd
# 判断字符事是不是一个标题
True
# 小写转大写,大写转小写
hELLO,wSD
Hello,Wsd
# 将首字母转换为大写
Hello,wsd
三、判断类方法
1、Python3 isalpha()方法
Python isalpha() 方法检测字符串是否只由字母组成。
语法
isalpha()方法语法:
str.isalpha()
参数
无。
返回值
如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。
实例
str = "runoob";
print str.isalpha();
str = "runoob小钢炮";
print str.isalpha();
str = "this is string example....wow!!!";
print str.isalpha();
以上实例输出结果如下:
True
False
False
2、Python3 isalnum()方法
Python isalnum() 方法检测字符串是否由字母和数字组成。
语法
isalnum()方法语法:
str.isalnum()
参数
无。
返回值
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
实例
以下实例展示了isalnum()方法的实例:
str = "this2009"; # 字符中没有空格
print str.isalnum();
str = "this is string example....wow!!!";
print str.isalnum();
以上实例输出结果如下:
True
False
3、Python3 isspace()方法
Python isspace() 方法检测字符串是否只由空白字符组成。
语法
isspace() 方法语法:
str.isspace()
参数
无。
返回值
如果字符串中只包含空格/指标位/换行符,则返回 True,否则返回 False.
实例
以下实例展示了isspace()方法的实例:
str = " \n \t"
print (str.isspace())
str = "Runoob example....wow!!!"
print (str.isspace())
以上实例输出结果如下:
True
False
4、Python3 isdecimal()方法
Python isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。
语法
isdecimal()方法语法:
str.isdecimal()
参数
无
返回值
如果字符串是否只包含十进制字符返回True,否则返回False。
实例
以下实例展示了 isdecimal()函数的使用方法:
str = "runoob2016"
print (str.isdecimal())
str = "23443434"
print (str.isdecimal())
以上实例输出结果如下:
False
True
5、Python3 isdigit()方法
Python isdigit() 方法检测字符串是否只由数字组成。
语法
isdigit()方法语法:
str.isdigit()
参数
无。
返回值
如果字符串只包含数字则返回 True 否则返回 False。
实例
以下实例展示了isdigit()方法的实例:
str = "123456";
print (str.isdigit())
str = "Runoob example....wow!!!"
print (str.isdigit())
以上实例输出结果如下:
True
False
6、Python3 startswith()方法
startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
语法
startswith()方法语法:
str.startswith(substr, beg=0,end=len(string));
参数
str -- 检测的字符串。
substr -- 指定的子字符串。
strbeg -- 可选参数用于设置字符串检测的起始位置。
strend -- 可选参数用于设置字符串检测的结束位置。
返回值
如果检测到字符串则返回True,否则返回False。
实例
以下实例展示了startswith()函数的使用方法:
str = "this is string example....wow!!!"
print (str.startswith( 'this' )) # 字符串是否以 this 开头
print (str.startswith( 'string', 8 )) # 从第八个字符开始的字符串是否以 string 开头
print (str.startswith( 'this', 2, 4 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头
以上实例输出结果如下:
True
True
False
7、Python3 endswith()方法
endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。
语法
endswith()方法语法:
str.endswith(suffix[, start[, end]])
参数
suffix -- 该参数可以是一个字符串或者是一个元素。
start -- 字符串中的开始位置。
end -- 字符中结束位置。
返回值
如果字符串含有指定的后缀返回 True,否则返回 False。
实例
以下实例展示了endswith()方法的实例:
Str='Runoob example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='run'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
以上实例输出结果如下:
True
True
False
False
四、小练习
模拟用户注册,要求:
1、用户名不能是纯数字,不能以数字开头,必须包含数字、字母或者下划线其中两项。
2、用户密码长度在6-12位之间,不能是纯数字或纯字母,必须包含数字、字母大写或小写两项。
3、符合以上要求,程序提示注册成功;否则在输入内容之后立即给出错误提示。
def user():
while True:
username = input('请输入要注册的账号(不能是纯数字,不能以数字开头,必须包含数字、字母或者下划线其中两项')
if username == '' :
print('用户名不能为空')
continue
elif username .isdecimal() or username[0].isdecimal() == True:
print('用户名首字母不能为数字或不能为纯数字用户名' )
continue
elif username.isalpha() == True:
print('必须包含数字字母下 划线其中两项' )
continue
else:
return username
break
def password():
while True:
passwd = input(' 请输入密码: ')
if len(passwd) < 6 or len(passwd) > 12:
print( '用户密码长度在6 -12位之间')
continue
elif passwd. isdecimal() or passwd. isalpha():
print('用户密码不能是纯数字或纯字母,必须包含数字、字母大写或小写两项:')
continue
else:
return passwd
break
def xgp():
user()
password()
print('注册成功')
xgp()
以上实例输出结果如下:
请输入要注册的账号(不能是纯数字,不能以数字开头,必须包含数字、字母或者下划线其中两项f123
请输入密码: sdf456!weq.
注册成功
五、查找类的方法
str = 'hello,python'
print(str.find('p'))
print(str.index('e'))
print(str.rindex('o'))
print(str.rfind('h'))
以上实例输出结果如下:
6
1
10
9
1、Python3 find()方法
find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。
语法
find()方法语法:
str.find(str, beg=0, end=len(string))
参数
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
返回值
如果包含子字符串返回开始的索引值,否则返回-1。
实例
以下实例展示了find()方法的实例:
str1 = "Runoob example....wow!!!"
str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))
以上实例输出结果如下:
7
7
-1
例子
>>>info = 'abca'
>>> print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
0
>>> print(info.find('a', 1)) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
3
>>> print(info.find('3')) # 查找不到返回-1
-1
2、Python3 index()方法
index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
语法
index()方法语法:
str.index(str, beg=0, end=len(string))
参数
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
返回值
如果包含子字符串返回开始的索引值,否则抛出异常。
实例
以下实例展示了index()方法的实例:
str1 = "Runoob example....wow!!!"
str2 = "exam";
print (str1.index(str2))
print (str1.index(str2, 5))
print (str1.index(str2, 10))
以上实例输出结果如下(未发现的会出现异常信息):
7
7
Traceback (most recent call last):
File "test.py", line 8, in
print (str1.index(str2, 10))
ValueError: substring not found
3、Python3 rfind()方法
Python rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
语法
rfind()方法语法:
str.rfind(str, beg=0 end=len(string))
参数
str -- 查找的字符串
beg -- 开始查找的位置,默认为0
end -- 结束查找位置,默认为字符串的长度。
返回值
返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
实例
以下实例展示了rfind()函数的使用方法:
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))
print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))
以上实例输出结果如下:
5
5
-1
2
2
-1
4、Python3 rindex()方法
rindex() 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
语法
rindex()方法语法:
str.rindex(str, beg=0 end=len(string))
参数
str -- 查找的字符串
beg -- 开始查找的位置,默认为0
end -- 结束查找位置,默认为字符串的长度。
返回值
返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常。
实例
以下实例展示了rindex()函数的使用方法:
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.rindex(str2,10))
以上实例输出结果如下:
5
Traceback (most recent call last):
File "test.py", line 6, in <module>
print (str1.rindex(str2,10))
ValueError: substring not found
六、小练习
(1)练习
验证规则:
正确格式:abc@163.com.cn
1、邮箱必须包含“@”和“.”
2、“@”在邮箱字符串中不能是第一个位置
3、“.”右侧至少应该有2-3个字符
4、“.”左侧不能是“@”
def vanzheng():
youxiang = input(' 输入您的邮箱:')
num = youxiang.index('.')
qiepian = youxiang[num:-1]
if youxiang[0] =='@' or youxiang[0] == '.' :
print('邮箱第一位不能是@或者“.” ')
elif '.' not in youxiang or '@' not in youxiang:
print('邮箱必须包含“@”和“”')
elif len(qiepian) <= 2:
print('“.”右侧至少应该有2-3个字符')
elif youxiang[-1] == '@' or youxiang[-1] == '.':
print('邮箱最后一位不能是@或者.')
else:
print('邮箱正确')
vanzheng()
yx=input('请输入您的邮箱')
at = yx.find('@' )
dian = yx. find('.')
if (at <= 0 or dian <=0) or yx[-1]== '.' or (dian - at) <=1 :
print('邮箱格式有误' )
以上实例输出结果如下:
输入您的邮箱:123@qq.com
邮箱正确
(2)练习
1、提取passwd文件最后5个用户的记录
2、把每个用户的信息按“:”分别提取用户名、所属组、家目录、登录的shell类型
user_info = '''postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
test-07:x:1000:1000:test-07:/home/test-07:/bin/bash
chou:x:1003:1003::/home/chouchou:/bin/bash
test02:x:1002:1007::/home/test001:/bin/bash
try:x:1004:1004::/home/try:/bin/bash
laoyu:x:1005:1009::/home/laoyu:/bin/bash'''
new_info = user_info.split('\n')
for i in new_info:
print('用户名:'+i.split(':')[0]+'所属组:'+i.split(':')[4]+'家目录:'+i.split(':')[5]+'登录环境:'+i.split(':')[6])
以上实例输出结果如下:
用户名:postfix所属组:家目录:/var/spool/postfix登录环境:/sbin/nologin
用户名:tcpdump所属组:家目录:/登录环境:/sbin/nologin
用户名:test-07所属组:test-07家目录:/home/test-07登录环境:/bin/bash
用户名:chou所属组:家目录:/home/chouchou登录环境:/bin/bash
用户名:test02所属组:家目录:/home/test001登录环境:/bin/bash
用户名:try所属组:家目录:/home/try登录环境:/bin/bash
用户名:laoyu所属组:家目录:/home/laoyu登录环境:/bin/bash
七、其他方法
1、Python3 split()方法
split() 通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。
语法
split() 方法语法:
str.split(str="", num=string.count(str))
参数
str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num -- 分割次数。默认为 -1, 即分隔所有。
返回值
返回分割后的字符串列表。
实例
以下实例展示了 split() 函数的使用方法:
str = "this is string example....wow!!!"
print (str.split( )) # 以空格为分隔符
print (str.split('i',1)) # 以 i 为分隔符
print (str.split('w')) # 以 w 为分隔符
(1)以下实例以 # 号为分隔符,指定第二个参数为 1,返回两个参数列表。
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
print(x)
以上实例输出结果如下:
['Google', 'Runoob#Taobao#Facebook']
2、Python3 join()方法
Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
语法
join()方法语法:
str.join(sequence)
参数
sequence -- 要连接的元素序列。
返回值
返回通过指定字符连接序列中元素后生成的新字符串。
实例
以下实例展示了join()的使用方法:
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))
以上实例输出结果如下:
r-u-n-o-o-b
runoob
3、Python3中 strip lstrip rstrip的使用方法
简单来说,三种方法是为了删除字符串中不同位置的指定字符。其中,strip()用于去除字符串的首尾字符,同理,lstrip()用于去除左边的字符,rstrip()用于去除右边的字符
(1)strip()
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
若传入的是一个字符数组,编译器将去除字符串两端所有相应的字符,直到没有匹配的字符。
语法
str.strip([chars])
参数
chars – 移除字符串头尾指定的字符。
实例
1、默认方法
string1 = ' Kobe Bryant '
print(string1.strip())
以上实例输出结果如下:
Kobe Bryant
默认删除字符串前后的空格。
2、 参数传递
string2 = 'uuuussssaaaa china aaaassssuuu'
print(string2.strip('usa'))
以上实例输出结果如下:
china
其中, 'u'、's'、'a' 的个数可以为任意,不影响最后输出 > china
(2)lstrip()
Python lstrip() 方法用于截掉字符串左边的空格或指定字符,默认为空格。
实例
1、默认方法
string1 = ' Kobe Bryant '
string1.lstrip()
以上实例输出结果如下:
'Kobe Bryant '
默认删除字符串前的空格。
2、 参数传递
string2 = 'uuuussssaaaa china aaaassssuuu'
print(string2.strip('usa'))
以上实例输出结果如下:
china aaaassssuuu
(3)rstrip()
Python lstrip() 方法用于截掉字符串右边的空格或指定字符,默认为空格。
实例
1、默认方法
string1 = ' Kobe Bryant '
string1.lstrip()
以上实例输出结果如下:
Kobe Bryant'
默认删除字符串后的空格。
2、参数传递
string2 = 'uuuussssaaaa china aaaassssuuu'
print(string2.strip('usa'))
以上实例输出结果如下:
uuuussssaaaa china
4、Python3 replace()方法
描述
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法
replace()方法语法:
str.replace(old, new[, max])
参数
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
实例
以下实例展示了replace()函数的使用方法:
str = "wsdixgp.top"
print ("xgp旧地址:", str)
print ("xgp新地址:", str.replace("wsdixgp.top", "wsdlxgp.top"))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
以上实例输出结果如下:
xgp旧地址: wsdixgp.top
xgp新地址: wsdlxgp.top
thwas was string example....wow!!!
八、使用Python分析Apache的访问日志
1、字符串分割
创建access.log文件(存放日志信息即可)
log = '182.19.31.129 - - [16/JAN/2020:06:05:35 +0200] "GET /index.php HTTP/1.1" 200 0 "-" "Mozilla/5.0 (compatible; PJBot/3.0; +http://craw1.pagesjaunes.fr/robot)" "-"'
log_temp = log.split()
print(log_temp)
print('用户IP:'+log_temp[0])
print('访问页面:'+log_temp[6])
print('状态码:'+log_temp[8])
from __future__ import print_function
ips = []
with open('access.log') as f:
for line in f:
ips.append(line.split()[0])
print('网站请求数[PV]:'+ str(len(ips)))
print('网站独立的访客数[UV]:'+ str(len(set(ips))))
以上实例输出结果如下:
网站请求数[PV]:120
网站独立的访客数[UV]:6
2、使用counter类统计PV和UV
from __future__ import print_function
d = {}
with open('access.log') as f:
for line in f:
key = line.split()[8]
d.setdefault(key,0)
d[key] += 1
print(d)
# 出错的页面数量
error_requests = 0
# 页面总访问量
sum_requests = 0
# 遍历字典
for key, value in d.items():
if int(key) >= 400:
error_requests += value
sum_requests += value
print('页面出错率:{0:2f}%'.format(error_requests * 100.0/sum_requests))
以上实例输出结果如下:
{'200': 115, '500': 1, '248': 1, '210': 1, '203': 1, '400': 1}
页面出错率:1.666667%
九、格式化
1、Python字符串格式化
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。
print ("我叫 %s 今年 %d 岁!" % ('小名', 10))
以上实例输出结果:
我叫 小名 今年 10 岁!
python字符串格式化符号:
符 号
描述
%c
格式化字符及其ASCII码
%s
格式化字符串
%d
格式化整数
%u
格式化无符号整型
%o
格式化无符号八进制数
%x
格式化无符号十六进制数
%X
格式化无符号十六进制数(大写)
%f
格式化浮点数字,可指定小数点后的精度
%e
用科学计数法格式化浮点数
%E
作用同%e,用科学计数法格式化浮点数
%g
%f和%e的简写
%G
%f 和 %E 的简写
%p
用十六进制数格式化变量的地址
格式化操作符辅助指令:
符号
功能
*
定义宽度或者小数点精度
-
用做左对齐
+
在正数前面显示加号( + )
在正数前面显示空格
#
在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0
显示的数字前面填充'0'而不是默认的空格
%
'%%'输出一个单一的'%'
(var)
映射变量(字典参数)
m.n.
m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
练习
rint( '%d' % 3)
print( '%09f' % 3.14)
print('%s' % 'hello')
以上实例输出结果如下:
3
03.140000
hello
2、format函数
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
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="xgp", url="wsdlxgp.top"))
# 通过字典设置参数
site = {"name": "xgp", "url": "wsdlxgp.top"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['xgp', 'wsdlxgp.top']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
以上实例输出结果如下:
网站名:xgp, 地址 wsdlxgp.top
网站名:xgp, 地址 wsdlxgp.top
网站名:xgp, 地址 wsdlxgp.top
也可以向 str.format() 传入对象:
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
以上实例输出结果如下:
value 为: 6
3、数字格式化
下表展示了 str.format() 格式化数字的多种方法:
数字
格式
输出
描述
3.1415926
{:.2f}
3.14
保留小数点后两位
3.1415926
{:+.2f}
+3.14
带符号保留小数点后两位
-1
{:+.2f}
-1.00
带符号保留小数点后两位
2.71828
{:.0f}
3
不带小数
5
{:0>2d}
05
数字补零 (填充左边, 宽度为2)
5
{:x<4d}
5xxx
数字补x (填充右边, 宽度为4)
10
{:x<4d}
10xx
数字补x (填充右边, 宽度为4)
1000000
{:,}
1,000,000
以逗号分隔的数字格式
0.25
{:.2%}
25.00%
百分比格式
1000000000
{:.2e}
1.00e+09
指数记法
13
{:>10d}
13
右对齐 (默认, 宽度为10)
13
{:<10d}
13
左对齐 (宽度为10)
13
{:^10d}
13
中间对齐 (宽度为10)
11
'{:b}'.format(11) '{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11) '{:#x}'.format(11) '{:#X}'.format(11)
1011 11 13 b 0xb 0XB
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
# 精度
print('{: .2f}'.format(3.141592656535897))
# 符号
print('{: .2f}'.format(3.141592656535897))
# 宽度
print( '{:10.2f}'.format(3.141592656535897))
# 对齐方式
print('{:^10.2f}'.format(3.141592656535897))
# 逗号分隔
print('{:,}'.format(23421424231))
以上实例输出结果如下:
3.14
3.14
3.14
3.14
23,421,424,231
此外我们可以使用大括号 {} 来转义大括号,如下实例:
print ("{} 对应的位置是 {{0}}".format("runoob"))
以上实例输出结果如下:
runoob 对应的位置是 {0}
python中find函数忽略大小写_python字符串(大小写、判断、查找、分割、拼接、裁剪、替换、格式化)...相关推荐
- python中isdigit函数什么意思_python字符串是否为数字类型-python isdigit函数-isdigit函数 python-python isdigit函数使用-嗨客网...
Python字符串是否是数字教程 在开发过程中,有时候我们需要判断一个 Python isdigit()函数详解 语法 str.isdigit() -> bool 参数 参数 描述 str 表示 ...
- python中reduce函数的运用_python 中 reduce 函数的使用
reduce()函数也是Python内置的一个高阶函数. reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接 ...
- python中int函数的功能_python中int函数是什么意思
摘要 腾兴网为您分享:python中int函数是什么意思,小t智联,未来屋,唯品会,围棋宝典等软件知识,以及么么聊天,daemontoolslite,鼠标自动连点器,河南校信通,时尚魔女,帮兼职,红包 ...
- python中choice()函数的参数_Python中choice函数如何实现?
熟悉Python的小伙伴是知道Python是可以生成随机项的,python中choice函数是random模块的随即取样函数,它可以通过导入 random 模块,调用 random 静态对象生成Pyt ...
- python中zip()函数的用法_Python zip()函数用法实例分析
本文实例讲述了python zip()函数用法.分享给大家供大家参考,具体如下: 这里介绍python中zip()函数的使用: >>> help(zip) Help on built ...
- python中定义函数常用关键字_Python 中定义函数的关键字是 _________________ 。_学小易找答案...
[其它]实验4-串和数组-实验任务书.docx [填空题]表达式 'abc' in ['abcdefg'] 的值为______________. [填空题]已知 x = range(1,4) 和 y ...
- python中pop函数的用法_python中pop()函数怎么用
python中pop()函数的用法:pop()函数用于移除列表中的一个元素(默认最后一个元素),并且返回从列表中移除的元素对象.函数语法:[list.pop(ojb=list[-1])]. pop() ...
- python中append函数什么意思_python中append函数用法讲解
python中append函数用法讲解 如果在做一个地区的统计工作,可以使用列表来帮助我们.输入汉字或者其他字符,比如"01代表汉族",那么在写民族的时候有下拉列表,就可以打01, ...
- python中divmod函数的用法_Python中divmod函数的用法
Python中divmod函数的用法,语言,余数,是一种,面向对象,函数 Python中divmod函数的用法 Python中divmod函数的用法 在Python中divmod函数的作用是把除数和余 ...
- python中pow函数的用法_python中pow函数用法及功能说明
幂运算是高更数学的应用学科,是一种关于幂的数学运算.同底数幂相乘,底数不变,指数相加.同底数幂相除,底数不变,指数相减.幂的乘方,底数不变,指数相乘.适用于精确计算领域. 计算机作为精确计算的一种方式 ...
最新文章
- 开源服务专题之------ssh防止暴力破解及fail2ban的使用方法
- vuex数据管理-数据适配
- ios 添加浮动效果_iOS实现拖拽View跟随手指浮动效果
- Python 的列表的一些方法
- 面试系列12 redis和memcached有什么区别
- java webservice https_WebService的HTTPS访问——解决PKIX错误 | 字痕随行
- jedis开发过程中遇到的问题及其解决方法
- VB更改任何标题程序源代码
- 华为平板电脑_华为MatePad Pro 5G:云游戏、云电脑加持,这台平板不只是平板
- 【渝粤教育】国家开放大学2018年秋季 0056-21T知识产权法 参考试题
- 开源巨献:腾讯最热门30款开源项目
- 【铨顺宏项目推荐】RFID无线射频识别技术的设计思路
- rk3568 LTE(EC20)
- Qt Designer简介
- 2021-07-03 dd命令拷贝数据错误的问题定位及解决方法
- c++ 迷宫思路_C++实现简单走迷宫的代码
- H.264/AVC标准参考软件 JM
- 【性能优化】MySQL常用慢查询分析工具
- 《javascript语言精粹》读书笔记——函数
- Lwip协议详解(基于Lwip 2.1.0)-ICMP协议 (未完待续)
热门文章
- 用iptables来防止web服务器被CC攻击
- qt 连接mysql
- dhtmlxtree api中文
- 10个不为人知 但绝对值得收藏的网站
- 加密解密时遇到的不正确的数据以及要解密的数据长度无效问题解决方案
- python计算n的32次方_获得用户输入的一个整数N,计算并输出N的32次方。_学小易找答案...
- 1.3 更多边缘检测内容-深度学习第四课《卷积神经网络》-Stanford吴恩达教授
- TCL with SNPS collection_limitget_lib_pins
- 实验开篇介绍---开发板介绍
- 类和对象—对象特性—深拷贝与浅拷贝