繁体   English   中英

在特定字符长度上按字格式化字符串

[英]Formatting a string by word at a specific character length

我在数据库中的任何地方都没有看到这个问题 - 如果它是重复的,请告诉我!

我正在尝试将字符串格式化为一定长度; 我有一个任意长度的字符串,我只想在每n个字符中添加换行符,用单词分隔,这样字符串就不会在单词的中间分割。

str = "This is a string with length of some arbitrary number greater than 20"
count=0
tmp=""
for word in str.split():
   tmp += word + " "
   count += len(word + " ")
   if count > 20:
      tmp += "\n"
      count = 0
str = tmp
print str

我确信有一种令人尴尬的简单Pythonic方法可以做到这一点,但我不知道它是什么。

建议?

使用textwrap模块。 对于你的情况textwrap.fill应该有它:

>>> import textwrap
>>> s = "This is a string with length of some arbitrary number greater than 20"
>>> print textwrap.fill(s, 20)
This is a string
with length of some
arbitrary number
greater than 20

这可能不是最直接的方式,它效率不高,但它概述了pythonic one liners中的过程:

def example_text_wrap_function(takes_a_string,by_split_character,line_length_int):
    str_list = takes_a_string.split(by_split_character)
    tot_line_length = 0
    line = ""
    line_list = []
    for word in str_list:
        # line_length_int - 1 to account for \n
        if len(line) < (line_length_int - 1):
            # check if first word
            if line is '':
                line = ''.join([line,word])
            # Check if last character is the split_character
            elif line[:-1] is by_split_character:
                line = ''.join([line,word])
            # else join by_split_character
            else:
                line = by_split_character.join([line,word])
        if len(line) >= (line_length_int - 1):
            # last word put len(line) over line_length_int start new line
            # split(by_split_character)
            # append line from range 0 to 2nd to last "[0:-2]" and \n
            # to line_list
            list_out = by_split_character.join(line.split(by_split_character)[0:-1]), '\n'
            str_out = by_split_character.join(list_out)
            line_list.append(str_out)
            # set line to last_word and continue
            last_word = line.split(by_split_character)[-1]
            line = last_word
        # append the last line if word is last
        if word in str_list[-1]:
            line_list.append(line)

    print(line_list)


    for line in line_list:
        print(len(line))
        print(repr(line))
    return ''.join(line_list)

# if the script is being run as the main script 'python file_with_this_code.py'
# the code below here will run. otherwise you could save this in a file_name.py
# and in a another script you could "import file_name" and as a module
# and do something like file_name.example_text_wrap_function(str,char,int)

if __name__ == '__main__':

    tmp_str = "This is a string with length of some arbitrary number greater than 20"
    results = example_text_wrap_function(tmp_str,' ',20)
    print(results)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM