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

时间:2014-04-06 00:40:47

标签: python string split format

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

我试图按字词将字符串格式化为一定长度;我有一个任意长度的字符串,我只想在每个 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方法可以做到这一点,但我不知道它是什么。

建议?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这可能不是最直接的方式,它效率不高,但它概述了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)