【问题标题】:How to store the last n characters of a string to concatenate to the user input in Python?如何存储字符串的最后 n 个字符以连接到 Python 中的用户输入?
【发布时间】:2023-03-28 22:45:01
【问题描述】:

在 Head First Learn to Code 中有一个简短的练习,其中涉及创建一个函数来替换文本中的占位符。如果占位符的结尾是 !!!!!,则此代码仅返回最后一个感叹号。我们如何修改代码,以便当用户提供单词 SPAM 作为输入代替 NOUN!!!, 时,processed_line 将返回 SPAM!! !,?

这是代码:

placeholders = ['NOUN', 'VERB_ING', 'ADJECTIVE', 'VERB']
endings = ['.', ',', ';', ':', '?', '!']


def process_line(line):
    global placeholders
    global endings
    processed_line = ''

    words = line.split()


    for word in words:
        stripped = word.strip(',.;:?!')
        if stripped in placeholders:
            answer = input(f'Enter a {stripped}:')
            processed_line = processed_line + answer
            if word[-1] in endings:
                processed_line = processed_line + word[-1] + ' '
            else:
                processed_line = processed_line + ' '
        else:
            processed_line = processed_line + word + ' '
    return processed_line + '\n'

【问题讨论】:

  • 你能解释一下你想要做的更多吗?你也没有提到问题到底是什么。
  • 问题是它应该只改变占位符,而不是标点符号。使用 if word[-1] in endings:I 可以检索最后一个标点符号。但我想用输入返回不确定数量的标点符号。例如,如果我们找到像 VERB!!!!*NOUN!!? 这样的东西,它会返回 EATING!!!!和垃圾邮件!!?而不仅仅是吃!和垃圾邮件?

标签: python string replace concatenation slice


【解决方案1】:

你一开始就去掉了标点符号。稍后再添加它们,它应该可以工作:

placeholders = ['NOUN', 'VERB_ING', 'ADJECTIVE', 'VERB']
endings = ['.', ',', ';', ':', '?', '!']


def process_line(line):
    global placeholders
    global endings
    processed_line = ''

    words = line.split()

    def keep(string, chars):
      return ''.join([i for i in string if i in chars])

    for word in words:
        stripped = word.strip(',.;:?!')
        leftovers = keep(word, ',.;:?!')
        if stripped in placeholders:
            loc = placeholders.index(stripped)
            answer = input(f'Enter a {stripped}:')
            processed_line += answer + leftovers # here is what's new
            if word[-1] in endings:
                processed_line = processed_line + word[-1] + ' '
            else:
                processed_line = processed_line + ' '
        else:
            processed_line = processed_line + word + ' '
    return processed_line + '\n'

print(process_line('hello, NOUN! I am Joe.'))

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多