我有这个代码(打印字符串中所有排列的出现)
def splitter(str):
for i in range(1, len(str)):
start = str[0:i]
end = str[i:]
yield (start, end)
for split in splitter(end):
result = [start]
result.extend(split)
yield result
el =[];
string = "abcd"
for b in splitter("abcd"):
el.extend(b);
unique = sorted(set(el));
for prefix in unique:
if prefix != "":
print "value " , prefix , "- num of occurrences = " , string.count(str(prefix));
我想打印字符串变量中的所有排列。
因为排列的长度不一样,我想固定宽度,然后打印成一个很好的而不是这个:
value a - num of occurrences = 1
value ab - num of occurrences = 1
value abc - num of occurrences = 1
value b - num of occurrences = 1
value bc - num of occurrences = 1
value bcd - num of occurrences = 1
value c - num of occurrences = 1
value cd - num of occurrences = 1
value d - num of occurrences = 1
我怎么能用format
来做呢?
我找到了这些帖子,但与字母数字字符串的搭配不太好:
最初是作为@0x90答案的编辑发布的,但由于偏离了帖子的初衷而被拒绝,建议作为评论或答案发布,所以我在这里包括了简短的评论。
除了@0x90的答案外,还可以通过使用宽度变量(根据@user2763554的注释)使语法更加灵活:
此外,通过仅使用数字并依赖传递给
format
的参数的顺序,可以使此表达式更简洁:或者甚至为最大的、潜在的非pythonical隐式紧性忽略所有数字:
更新2017-05-26
使用Python 3.6中的the introduction of formatted string literals(简称“f-strings”),现在可以使用更简洁的语法访问先前定义的变量:
这也适用于字符串格式
我发现使用
str.format
更优雅:如果要将字符串正确对齐,请使用
>
,而不是<
:编辑: 如注释中所述:0表示传递给
str.format()
的参数索引。编辑2013-12-11-这个答案很古老。它仍然有效且正确,但是人们看到它时应该更喜欢new format syntax。
您可以像这样使用string formatting:
基本上:
%
字符通知python它将不得不用某种东西替换令牌s
字符通知python令牌将是一个字符串5
(或您想要的任何数字)通知python用最多5个字符的空格填充字符串。在您的特定情况下,可能的实现可能如下所示:
旁注:只是想知道您是否知道^{} module 的存在。例如,您可以在一行中获得所有组合的列表:
您可以通过将
combinations
与count()
结合使用来获得出现的次数。相关问题 更多 >
编程相关推荐