按特定字符长度逐字格式化字符串

2024-04-19 05:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图用单词将字符串格式化为一定长度;我有一个任意长度的字符串,我只想在每个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

我确信有一种简单得让人尴尬的Python式的方法来做这件事,但我不知道它是什么。在

建议?在


Tags: of字符串数据库stringiscountwiththis
2条回答

使用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一行程序中的过程:

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)

相关问题 更多 >