簡體   English   中英

如何編寫接收字符串消息並返回帶有分頁的字符串消息列表的函數

[英]How to write function that takes in a string message and returns a list of string messages with pagination

我想編寫一個接受字符串消息並在需要時返回帶有分頁的字符串消息列表的函數。

這就是我所擁有的

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)

您不能在此處使用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與Smith博士約好。 如果您無法做出(1/3)
預約后,請至少在預定時間(2/3)前1小時致電我們的客戶服務熱線
預約時間。 (3/3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM