python 中我的字符计数器有问题

Problem with my character counter in python

我正在尝试在 python 中编写一个程序来计算文本中的字符数。当我输入没有像 Hello world! 这样的新行的文本并说有 12 个字符但是当我输入像

这样的东西时它工作
Hello
world!

那就只算第一行,说有5个字符。 )=

我的代码:

import time

print("Please answer Y or N to the following questions:")
whatTo1Do = input("Would you like to include spaces in the character count? " )
whatTo2Do = input("Would you like to include commas in the character count? " )
whatTo3Do = input("Would you like to include apostrophes in the character count? " )
whatTo4Do = input("Would you like to include maths symbols (+, <, ÷, etc.) in the character count? " )
whatTo5Do = input("Would you like to include brackets in the character count? " )
whatTo6Do = input("Would you like to include other characters (~, `, \, %, &, etc.) in the character count? " )
yas = input("Your settings are displayed above. Are they correct? ")
if yas == "Y":
    pass
elif yas == "N":
    print("Please press OK to restart.")
    time.sleep(1)
    exit()
text = input("Enter your text here to count the characters based on your settings above: ")
if whatTo1Do == "N" or whatTo1Do == "n" or whatTo1Do == "no":
    text.replace(" ", "")
if whatTo2Do == "N" or whatTo2Do == "n" or whatTo2Do == "no":
    text.replace(",", "")
if whatTo3Do == "N" or whatTo3Do == "n" or whatTo3Do == "no":
    text.replace("'", "")
    text.replace('"', "")
if whatTo4Do == "N" or whatTo3Do == "n" or whatTo3Do == "no":
    text.replace("×", "")
    text.replace("÷", "")
    text.replace("=", "")
    text.replace("-", "")
    text.replace("+", "")
    text.replace(">", "")
    text.replace("<", "")
    text.replace("^", "")
    text.replace("*", "")
if whatTo5Do == "N" or whatTo3Do == "n" or whatTo3Do == "no":
    text.replace("[", "")
    text.replace("]", "")
    text.replace("(", "")
    text.replace(")", "")
    text.replace("{", "")
    text.replace("}", "")
if whatTo6Do == "N" or whatTo3Do == "n" or whatTo3Do == "no":
    text.replace("~", "")
    text.replace("`", "")
    text.replace("@", "")
    text.replace("#", "")
    text.replace("$", "")
    text.replace("%", "")
    text.replace("&", "")
    text.replace("\ ", "")
    text.replace(" \ ", "")
    text.replace("|", "")
    text.replace("/", "")
print("There are", len(text), "characters in your text. (=")

我该怎么做才能让它计算两行?

在您提到粘贴多字符串输入后,我意识到了问题(以及您可能的解决方案)。 input 只读取评论中提到的单行,但看起来您需要读取多行输入。

您可以使用下面的辅助函数 multi_line_input 来做到这一点。当用户输入空字符串(空白输入)时它将中断。然后在你的代码中你可以像往常一样得到这个字符串的长度,它应该可以工作。

def multi_line_input(prompt: str = '') -> str:
    """Reads multiple line from user input. An empty line breaks the loop."""
    lines = []
    while True:
        line = input(prompt)
        if line:
            # Note: added strip() here to strip out spaces at end,
            # such as 'hello '
            lines.append(line.rstrip())
        else:
            break
    return '\n'.join(lines)