python自2.6后,新增了一种格式化字符串函数str.format(),威力十足,可以替换掉原来的% 注:以下操作版本是python2.7 映射示例 语法 通过{} 和 : 替换 % 通过位置 >>> '{0} is {1}'.format('jihite', '4 years old') 'jihite is 4 years old' >>> '{0} is {1} {0}'.format('jihite', '4 years old') 'jihite is
.format字符串拼接 # -*- coding:utf8 -*- #不一一对应会报错 tp1 = "i am {}, age {}, {}".format("charon",18,"pluto") print(tp1) tp2 = "i am {2}, age {0}, {1}".format("charon",18,"pluto") print(tp2) tp2 = "i
# format() 方法 {}代替元素 默认是从左往右开始取值 test = 'i am {},age {},{}'.format('xiaoma',18,'happy') print(test) i am xiaoma,age 18,happy test1 = ','xiaoma','happy') print(test1) i am xiaoma,age 18,happy test2 = ','xiaoma','happy') print(test2) i am 18,age 18,18
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator. 1.百分号
1.字符串连接 >>> a = 'My name is ' + 'Suen' >>> a 'My name is Suen' >>> a = 'My name is %s'%'Suen' >>> a 'My name is Suen' >>> a = 'My name is %s, Age:%d'%('Suen', 18) >>> a 'My name is Suen, Age:18'>>
下面是某个字符串是否为IP地址import re def isIP(str): p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') if p.match(str): return True else: return FalsemyStr = "10.69.36.95"if isIP(myStr): print(myStr,"it is a IP!"
Your ''.join() expression is filtering, removing anything non-ASCII; you could use a conditional expression instead: return ''.join([i if ord(i) < 128 else ' ' for i in text]) This handles characters one by one and would still use one space per chara