如何编写接收字符串消息并返回带有分页的字符串消息列表的函数

时间:2019-04-17 23:47:17

标签: python python-3.x

我想编写一个接收字符串消息并在需要时返回带有分页的字符串消息列表的函数。

这就是我所拥有的

import textwrap

def smart_collect():
    text = input('Please Enter a text: ')
    dedented_text = textwrap.dedent(text).strip()
    wrap_text = textwrap.wrap(dedented_text, width=212)
    max_page = len(wrap_text)

    for i in range(0, max_page):
        print(f'{wrap_text[i]} ({i+1}/{max_page})')


smart_collect()

输入文字/字符串:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service line at least 1 hour before your scheduled 
appointment time.

我的输出:

As a reminder, you have an appointment with Dr. Smith tomorrow at(1/1)
3:30 pm. If you are unable to make this appointment, please call our 
3:30: command not found
customer service line at least 1 hour before your scheduled customer: 
command not found
appointment time.

预期结果

例如,以下消息具有212个字符:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service line at least 1 hour before your scheduled 
appointment time.

消息应按以下两个块发送:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service  (1/2)

line at least 1 hour before your scheduled appointment time. (2/2)

1 个答案:

答案 0 :(得分:1)

您不能出于自己的目的在这里使用textwrap.fill()

  

将单个段落包装为文本,并返回包含已包装段落的单个字符串。

相反,您需要使用textwrap.wrap()

  

将单个段落包装为文本(字符串),因此每一行最多为宽度字符。返回输出行列表,不带最终换行符。

由于它已经返回了列表,因此您在这里没有什么可做的了。

def smart_collect():
    text = input('Please Enter a text: ')
    dedented_text = textwrap.dedent(text).strip()
    wrap_text = textwrap.wrap(dedented_text, width=100)
    return wrap_text

print(smart_collect())

现在您有了一个长度为width=100个字符的字符串列表,现在您可以对字符串进行任何操作。例如,如果要打印它们,可以这样做:

for each in smart_collect():
    print(each)

现在,如果您想添加分页,则可以执行以下操作:

list_strings = smart_collect()
max_page = len(list_strings)
for i in range(0, max_page):
    print(f'{list_strings[i]} ({i+1}/{max_page})')

对于您的输入,结果(宽度= 100)如下所示:

  

提醒您,您明天下午3:30与史密斯医生约好。如果您无法制作(1/3)
  此约会,请至少在预定时间(2/3)前1小时致电我们的客户服务热线
  预约时间。 (3/3)