繁体   English   中英

我如何限制输入中 python 中每行的字符数

[英]How would I limit the number of characters per line in python from an input

有没有办法限制每行打印的字符数?

  while 1:
    user_message = ""
    
    messageQ = input("""\nDo you want to enter a message?
  [1] Yes    
  [2] No

  [>] Select an option: """)
    if messageQ == "1":
      message = True
    elif messageQ == "2":
      message = False
    else:
      continue

    if message == True:
        print(
"""
-----------------------------------------------------------------

You can enter a custom message that is below 50 characters.
""")
    custom_message = input("""\nPlease enter your custom message:\n \n> """)
    if len(custom_message) > 50:
        print("[!] Only 50 characters allowed")
        continue
    
    else:
        print(f"""
Your Custom message is:
{custom_message}""") #here is where I need to limit the number of characters per line to 25
    
    
    break

所以我在这里打印它的地方:

Your Custom message is:
{custom_message}""") #here is where I need to limit the number of characters per line to 25

我需要将 output 限制为每行 25 个字符。

你可以做

message = "More than 25 characters in this message!"
print(f"{message:.25}")

Output

More than 25 characters i

您可以使用textwrap.fill将过长的字符串分成多行,示例用法

import textwrap
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
print(textwrap.fill(message, 25))

output

Lorem ipsum dolor sit
amet, consectetur
adipiscing elit, sed do
eiusmod tempor incididunt
ut labore et dolore magna
aliqua. Ut enim ad minim
veniam, quis nostrud
exercitation ullamco
laboris nisi ut aliquip
ex ea commodo consequat.
Duis aute irure dolor in
reprehenderit in
voluptate velit esse
cillum dolore eu fugiat
nulla pariatur. Excepteur
sint occaecat cupidatat
non proident, sunt in
culpa qui officia
deserunt mollit anim id
est laborum.
>>> my_str = """This is a really long message that is longer than 25 characters"""
#For 25 characters TOTAL
>>> print(f"This is your custom message: {my_str}"[:25])
'This is your custom messa'
#For 25 characters in custom message
>>> print(f"This is your custom message: {my_str[:25]}")
This is your custom message: This is a really long mes

这利用了 substring 运算符。 这将切断第 25 个字符之后的所有字符。

由于已经检查过消息不超过 50 个字符,我们只需要知道它的长度是多于还是少于 25 个字符。

ln = len(custom_message) -1 # because strings are 0 indexed
if ln  < 25:
  print(custom_message) 
else:
  print(f"This is your custom message: {my_str}"[:ln])
  print(f"This is your custom message: {my_str}"[25:ln])
``

暂无
暂无

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

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