多行字符串中的Python注释

问题描述 投票:0回答:5

假设我有一个像这样的字符串:

foo = '''
some
important
stuff
'''

可以在里面评论吗?例如:

foo = '''
some 
# important
stuff
'''
python comments
5个回答
2
投票

不。

'''
是多行字符串。 其中的任何内容都是字符串的一部分,甚至以
#
开头的行。

如果您需要快速注释/取消注释部分字符串并且您不介意使用函数,则可以滥用

str.join
:

foo = '\n'.join((
    'some',
    'important',
    'stuff',
))

print(foo)

输出

some
important
stuff

同时

foo = '\n'.join((
    'some',
#     'important',
    'stuff',
))

print(foo)

输出

some
stuff

1
投票

这是不可能的,因为 ''' 是一个多行字符串。它里面的所有东西都是一个字符串。如果您解释为什么需要它,我可以为您的问题想出其他解决方案。


1
投票

基本上没有。 你可以做类似的事情

f'''
one line
two line
{"# A comment"[:0]}
fourth line
'''

“{...}”将被替换为任何内容。不过会有一个空行。

您也可以删除空行,但是您需要在 beform 行上添加 {

f'''
one line
two line{
#"comment"[:0]}
three line
'''

0
投票

我在维护法学硕士的提示时遇到了这个问题。英语现在就是代码,随着提示的发展,我想评论不同部分背后的基本原理。

我创建了一个函数来删除以

#
字符开头的多行字符串中的任何行。

def remove_comments(text):
    lines = [line for line in text.split('\n') if not line.startswith('#')]
    return '\n'.join(lines)

prompt = """You are a agent that assists with ___.
# cut unnecessary chatter at end of replies
Do not show appreciation in your responses, say only what is necessary."""

remove_comments(prompt)
# 'You are a agent that assists with ___.\nDo not show appreciation in your responses, say only what is necessary.'

-1
投票

注释通常会过时,因为 IDE 不会维护和忽略它们。

一个函数怎么样,你仍然可以在那里添加你的评论,但至少我们有一些代码作为基础

def define_an_important_string() -> str:
    """
    some things here are important
    
    Returns: string with stuff (maybe important)

    """
    return '''
    some stuff
    '''
© www.soinside.com 2019 - 2024. All rights reserved.