英文:
Replacing the Print Command in a python script with a comment
问题
I want the above command/line to be replaced with a string:
"#系列",即将上述打印命令转换为在该命令中的“print”后面的文本前缀为“#”的注释。
英文:
I have the command below in a .py file
print(r"\n print series")
I want the above command/line to be replaced with a string:
"#series" ie convert the above print command into a comment prefixing the # symbol to the text following the "print" in the command above.
I am new to python. Please help.
This question was closed earlier as it was not clear what I was attempting to do. Hence, the explanation that follows:
The reason for doing this: I want to use print statements in a script for learning python/using as reference. Later, I want to change the print statement into a comment. Hence, I want to replace the beginning of the print statement with a # which will convert it into a comment. As there would be many such conversions, I wanted to do it programmatically using a string.replace or something else. Any suggestions to achieve this in another way are also welcome. Thanks.
答案1
得分: 1
If you want to do this within your script itself (as opposed to doing a find+replace on the code), what I'd suggest would be wrapping the print
calls in a function that you can switch off:
DEBUG = True
def debug_print(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
Then if you have a bunch of calls like:
debug_print("\n print series")
they will only print as long as DEBUG
is True
. When you want to turn off all those print statements, you can just edit that one line:
DEBUG = False
and now nothing prints.
英文:
If you want to do this within your script itself (as opposed to doing a find+replace on the code), what I'd suggest would be wrapping the print
calls in a function that you can switch off:
DEBUG = True
def debug_print(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
Then if you have a bunch of calls like:
debug_print(r"\n print series")
they will only print as long as DEBUG
is True
. When you want to turn off all those print statements, you can just edit that one line:
DEBUG = False
and now nothing prints.
答案2
得分: 0
这是一个使用正则表达式的简单解决方案
- 将命令存储为名为 'command' 的变量中的字符串。
- 使用正则表达式将 'print' 关键字替换为 '#' 符号并删除 '\n' 字符。确保使用 '.strip()' 删除任何前导或尾随空格。
import re command = r"\n print series" comment = re.sub(r"\bprint\b\s*&", "#", command.replace(r"\n", "")).strip() print(comment)
这应该输出#series
,希望对您有所帮助。
英文:
Here's a simple solution using regex
- Store the command as a string in a variable called 'command'.
- Substitute the 'print' keyword with a '#' symbol and remove the '\n' character using regex. Making sure to use '.strip()' to remove any leading or trailing spaces.
import re
command = r"\n print series"
comment = re.sub(r"\bprint\b\s*", "#", command.replace(r"\n", "")).strip()
print(comment)
This should output #series
, hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论