Python之字符串

  • 字符串处理:

mystr='''ping www.baidu.com

正在 Ping www.a.shifen.com [220.181.112.244] 具有 32 字节的数据
来自 220.181.112.244 的回复: 字节=32 时间=27ms TTL=55
来自 220.181.112.244 的回复: 字节=32 时间=33ms TTL=55
来自 220.181.112.244 的回复: 字节=32 时间=56ms TTL=55
来自 220.181.112.244 的回复: 字节=32 时间=30ms TTL=55

'''
print(mystr)
print("字符串总长度:",len(mystr))
print("字符串总行数:",mystr.count("\n"))

#查找
#IP
print("\n")
print("查找IP地址:")
print("IP地址开始的位置是:",mystr.find("220"))
start1=mystr.find("220")
print("IP地址结束的位置是:",mystr.find("]",start1))
end1=mystr.find("]",start1)
print("IP地址是:",mystr[start1:end1])

#TTL
print("\n")
print("查找TTL值:")
print("TTL开始的位置是:",mystr.find("T"))
start2=mystr.find("T")
print("TTL结束的位置是:",mystr.find("\n",start2))

#替换
print("\n")
print(mystr.replace(mystr[start1:end1],"6.6.6.6",1))

 执行结果:

Python之字符串

  • 字符串格式化: 

import time

name="pomelo"
sex="女"
age=18
weigh=50
phone="17100000000"

#%
print("方法1:%")
print("%-12s%-8s%-5d%-5.1f%15s"%(name,sex,age,weigh,phone))
print("\n")

#format
print("方法2:format")
print("{0:<12s}{1:<8s}{2:<5d}{3:<5.1f}{4:>15s}".format(name,sex,age,weigh,phone))
print("\n")

执行结果: 

Python之字符串