Python字符串格式化
1、常用百分号格式化方式:
STRING = "I am %s" %"alex" STRING = "I am %s age %d" %("alex", 18) STRING = "I am %(name)s age %(age)d" %({"name": "alex", "age": 18}) STRING = "percent %.2f" %99.97623 STRING = "I am %(pp).2f" %{"pp": 123.425556} STRING = "I am %(pp).2f %%" %{"pp": 123.425556}
2、常用format格式化方式:
STRING = "I am {}, age {}, {}".format("seven", 18, 'alex') STRING = "I am {}, age {}, {}".format(*["seven", 18, 'alex']) STRING = "I am {0}, age {1}, really {0}".format("seven", 18) STRING = "I am {0}, age {1}, really {0}".format(*["seven", 18]) STRING = "I am {name}, age {age}, really {name}".format(name="seven", age=18) STRING = "I am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) STRING = "I am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) STRING = "I am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) STRING = "I am {:s}, age {:d}".format(*["seven", 18]) STRING = "I am {name:s}, age {age:d}".format(name="seven", age=18) STRING = "I am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) STRING = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) STRING = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) STRING = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) STRING = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
3、python脚本指定编码的两种方式
#!/usr/bin/python # coding=utf-8 #!/usr/bin/python # -*- coding: utf-8 -*-
#!/usr/bin/env python # -*- coding: utf-8 -*- #远程执行命令 import os login = "{}@{}".format('root', 'ipaddrss') site_path = '/var/www/nginx' proname = 'test' def comand(login, site_path): os.system("ssh %s 'cd %s && for i in $(ls *.tar.gz);do tar xf $i;chown -R root.root ${i%%%%.*};done && rm -fr *.tar.gz && echo 远程命令执行成功 || echo 远程命令执行失败'" % (login, site_path)) os.system('ssh {login} "cd {site_path} && tar -zcf /tmp/{proname}/{proname}_$(date +%F).tar.gz {proname}"'.format(login=login, proname=proname, site_path=site_path)) if __name__ == '__main__': comand(login, site_path)
参考链接:
https://www.cnblogs.com/czqq/p/6108557.html
https://www.cnblogs.com/exusll/p/6393621.html?utm_source=tuicool&utm_medium=referral #字符串操作
https://www.crifan.com/python_head_meaning_for_usr_bin_python_coding_utf-8/