我会构建一个函数来拆分每个单词,然后将str.join 一个列表组合在一起作为数字。比如:
def length_mapping(s):
lengths = map(len, s.split())
result = "\n".join( [s, "".join([str(length) + ' '*length for length in lengths])] )
return result
更详细:
def length_mapping_verbose(s):
words = s.split() # get words from the sentence
lengths = [] # initialize an empty list to store lengths in
for word in words:
lengths.append(len(word))
# this is exactly:
# # lengths = [len(word) for word in words]
length_string = ""
for length in lengths:
length_string += str(length)
length_string += " " * length
# the number plus an amount of spaces equal to the number.
# this only works for single-digit word lengths.
# "supercalifragilisticexpialidocious" will break this! We'll fix it later
result = s + "\n" + length_string
return result
正如我之前提到的,很长的文字会打破这一点,因为我们会得到这样的结果
some short words with an unimaginably-large word in the middle
4 5 5 4 2 18 4 2 3 6
注意两位数长度单词右侧的长度是如何被一个额外的空格取代的?这是由于我们没有计算长度长度这一事实引起的一个错误,我们只是假设它是一个允许之后的空间。要修复它,我们可以这样做:
def length_mapping_safe(s):
lengths = map(len, s.split())
result = "\n".join( [s, " ".join([str(length) + " " * (length - len(str(length)) for length in lengths])] )
return result
也就是说:
" ".join( # join with spaces
[str(length) # a list of strings, each starting a length
+ ' ' * # plus a number of spaces equal to...
(length - len(str(length)) # the length minus the number of digits IN that length
for length in lengths]) # for each length in the string lengths
或者你可以用字符串格式做一些事情,比如:
def length_mapping_with_str_format(s):
word_formatter = "{{:{}}}"
words = s.split()
lengths = [str(len(word)) for word in words]
lengths_as_words = [word_formatter.format(L).format(L) for L in lengths]
result = "\n".join([s, " ".join(lengths_as_words)])