先用一个python脚本来描述下:
脚本实验的功能是统计系统内存的值、剩余值以及剩余值所占的百分比。
#! /usr/bin/python
with open('/proc/meminfo') as aa:
for line in aa:
if line.startswith('MemTotal'):
MemTotal = line.split()[1]
continue
if line.startswith('MemFree'):
MemFree = line.split()[1]
break
print "The Memory Total: {:.2f}".format(int(MemTotal)/1024.0) + 'M'
print "The Memory left: {:.2f}".format(int(MemFree)/1024.0) + 'M'
print "The Memory left percent: {:.2f}".format((int(MemFree)/1024.0)/(int(MemTotal)/1024.0)*100) + '%'
作用:判断字符串是否以指定字符或子字符串开头。
语法:
string.startswith(str, beg=0,end=len(string))
参数说明:
string: 被检测的字符串
str: 指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg: 设置字符串检测的起始位置(可选)
end: 设置字符串检测的结束位置(可选)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查
返回值
如果检测到字符串,则返回True,否则返回False。默认空字符为True
常用环境:用于if判断
>>> if s.startswith('hel'):
print "you are right"
else:
print "you are wrong"
you are right
二、分离字符串
string = "www.baidu.com.cn"
print(string.split('.'))
['www', 'baidu', 'com', 'cn']
print(string.split('.',2)) ## 分割两次(,,)
['www', 'baidu', 'com.cn']
print(string.split('.',2)[1])
baidu
u1, u2, u3 =string.split('.',2)
print(u1)—— www
print(u2)—— baidu
print(u3) ——com.cn
str="hello boy<[www.baidu.com]>byebye"
print(str.split("[")[1].split("]")[0])
www.baidu.com
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
下表展示了 str.format() 格式化数字的多种方法:
>>> print("{:.2f}".format(3.1415926));
3.14
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
此外我们可以使用大括号 {} 来转义大括号。