reading/recognizing 换行符\n

reading/recognizing new line operator \n

今天的问题很简单。

问题: 我无法让我的代码从 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 语句。忽略它。)

我搜索了一下,但现在我只是在用头撞墙。欢迎任何帮助。谢谢大家!

这里有一个稍微不同的解决方案,它循环处理消息而不是复制它:

i = 0
s = ""
for x in dummy:
    if x == '$': # Keep it
        s += message[i % len(message)]
        i += 1
    elif x == ' ': # Skip it
        s += ' '
        i += 1
    else: # A line break
        s += x
print(s)

如果

pattern='
$$$$$$$s
$$$$  $$
$$$$$$$$
'

然后

reprPtrn='\'\n$$$$$$$s\n$$$$  $$\n$$$$$$$$\n\''

reprPtrn[i]遍历每个字符,\\n由三个字符组成,所以条件永远不满足。 不过

pattern[i] is "\n":

将 return 在换行符处为真。

您还应该使用 elif 和一个单独的索引来跟随模式中的消息字符。

具有请求输出的完整代码:

def patternedMessage(msg, pattern):
##Set variables, create repr and long string
newBuild = ""
strRecycleInt = len(pattern) // len(msg)
longPattern = (msg * (strRecycleInt + 1))
# print(reprPtrn) ## to see what the computer sees
##Rudimenray switch build
lineCounter = 0
k = 0
for i in range(len(pattern)):
    if (pattern[i] is "\n"):
        newBuild = newBuild + "\n"
        # lineCounter += 1 ## testing for entering the for
    elif (pattern[i] != " "):
        newBuild = newBuild + longPattern[k]
        k += 1
    elif (pattern[i] is " "):
        newBuild = newBuild + " "
    # print(lineCounter) ## Not entering the for statement
return newBuild