【发布时间】:2020-05-31 22:01:35
【问题描述】:
今天很简单的问题。
问题: 我无法让我的代码从 repr 字符串中读取换行符。
期望的输出: 我有一条消息和虚拟变量。我想在虚拟变量上写消息,例如:
dummy:
$$$$$$$$
$$$$ $$
$$$$$$$$
Message:
Hello!!
Returns:
Hello!!H
ello He
llo!!Hel
What I'm currently getting:
Hello! Hello! Hello! Hello!
代码:
def patternedMessage(msg, pattern):
##Set variables, create repr and long string
newBuild = ""
reprPtrn = repr(pattern)
strRecycleInt = len(reprPtrn)//len(msg)
longPattern = (msg *(strRecycleInt+1))
#print(reprPtrn) ## to see what the computer sees
##Rudimenray switch build
lineCounter = 0
for i in range(len(reprPtrn)):
if (reprPtrn[i] == "\n"):
newBuild = newBuild + "\n"
#lineCounter += 1 ## testing for entering the for
if (reprPtrn[i] != " "):
newBuild = newBuild + longPattern[i]
if (reprPtrn[i] == " "):
newBuild = newBuild + " "
#print(lineCounter) ## Not entering the for statement
return newBuild
我离得很近。我基本上构建了一个简单的开关,除了操作员之外一切正常。我知道我在尝试让我的代码识别 \n 时做错了。 (我注释掉了虚拟计数器。我用它来查看我是否真的在输入 if 语句。忽略它。)
我搜索了一下,但现在我只是用头撞墙。欢迎任何帮助。谢谢大家!
【问题讨论】:
-
感谢您加入 Carcigenicate。我将包括我目前得到的输出。基本上,newBuild str 不会创建新行并将所有内容打印在一行上。
-
'\n'不是运算符。这是一个字符。 -
你不需要对pattern的
repr进行操作。只需按原样使用它就可以了。
标签: python if-statement newline