读取/识别换行符\ n

问题描述 投票:-1回答:2

今天很简单的问题。

问题:我无法从repr字符串获取代码来读取换行符。

所需输出:我有一条消息和虚拟变量。我想通过Dummy变量来写消息,例如:

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语句。忽略它。)

我搜寻了一下,但现在我的头撞在墙上。欢迎任何帮助。谢谢大家!

python if-statement newline
2个回答
1
投票

如果

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

然后

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

reprPtrn [i]遍历每个字符,\\ n由三个字符组成,因此永远不会满足该条件。但是

pattern[i] is "\n":

将在换行符处返回true。

您还应该使用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

0
投票

这里是一个略有不同的解决方案,它遍历消息而不是复制消息:

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)
© www.soinside.com 2019 - 2024. All rights reserved.