【问题标题】:reading/recognizing new line operator \n读取/识别换行符 \n
【发布时间】: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


【解决方案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

【讨论】:

  • 这非常有帮助!非常感谢。我需要一些时间来更好地理解repr。我认为我使用它非常漂亮。
【解决方案2】:

这是一个稍微不同的解决方案,它循环浏览消息而不是复制它:

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)

【讨论】:

    猜你喜欢
    • 2014-04-20
    • 1970-01-01
    • 2015-09-28
    • 2012-06-02
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多