Python:Loop:格式化字符串



我不知道如何表达这一点。我想打印:

_1__2__3__4_

以CCD_ 2作为其子串。格式化子字符串时,如何获取主字符串?(作为的快捷方式

for x in range(1,5):
    print "_%s_" % (x)

(尽管这会打印多行))

编辑:只需一行

你的意思是这样的吗?

 my_string = "".join(["_%d_" % i for i in xrange(1,5)])

它根据请求创建一个子字符串列表,然后使用空字符串作为分隔符连接列表中的项(请参阅str.join()文档)。

或者,您可以使用+=操作符通过循环添加到字符串中,尽管它速度慢得多,效率低得多:

s = ""
for x in range(1,5):
    s += "_%d_" % x
print s
print("_" + "__".join(map(str, xrange(1,5)))) +"_"
_1__2__3__4_


In [9]: timeit ("_" + "__".join(map(str,xrange(1,5)))) +"_"
1000000 loops, best of 3: 1.38 µs per loop

In [10]: timeit "".join(["_%d_" % i for i in xrange(1,5)])
100000 loops, best of 3: 3.19 µs per loop

如果你愿意,你可以保持你的风格。

如果您使用的是python 2.7:

from __future__ import print_function
for x in range(1,5):
    print("_%s_" % (x), sep = '', end = '')
print()

对于python 3.x,不需要导入。

python文档:https://docs.python.org/2.7/library/functions.html?highlight=print#print

Python 3:

print("_{}_".format("__".join(map(str,range(1,5)))))
_1__2__3__4_

Python 2:

print "_{0}_".format("__".join(map(str,range(1,5))))
_1__2__3__4_

最新更新