将字符附加到python中的字符串

问题描述 投票:0回答:3

我想解决以下问题:

字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)

P   A   H   N
A P L S I I G
Y   I   R

然后逐行阅读:“PAHNAPLSIIGYIR”

编写将采用字符串的代码并在给定多行的情况下进行此转换:

string convert(string s,int numRows);

我编写了以下代码,但是我在粗体行中遇到错误“TypeError:不支持的操作数类型为+:'NoneType'和'unicode'”

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows==1:
            return s

        templist=[None]*numRows
        ret=" "

        curRow=0
        goingDown=0
        for each_char in s:
            if templist[curRow]:
                templist[curRow]=each_char
            else:
                **templist[curRow]=templist[curRow] + each_char**
            if (curRow==numRow-1 or curRow == 0):
                goingDown = not goingDown
            if goingDown:
                curRow=curRow+1
            else:
                curRow=curRow-1

        for each_str in templist:
            ret=ret+each_str
        print ret

我在这做错了吗?如果有人可以在这里指出问题,那将会很棒。提前致谢

python string list concatenation
3个回答
1
投票

您的条件似乎在以下几行中颠倒过来:

        if templist[curRow]:
            templist[curRow]=each_char
        else:
            **templist[curRow]=templist[curRow] + each_char**

它可能应该是:

        if templist[curRow]:
            templist[curRow]=templist[curRow] + each_char
        else:
            templist[curRow]=each_char

如果该字符串已经存在(不是templist[curRow]),这确保它只附加到None中的字符串,因此避免了向None添加字符串的错误。

更好的方法可能是设置templist = [""] * numRows,即空字符串列表,然后使用templist[curRow] += each_char添加到它,这将始终有效,因为您可以将字符添加到空字符串。


0
投票

是的,你做错了什么。

线templist=[None]*numRows使你的templist变量持有一堆Nones。然后你继续使用其中一个Nones,并尝试将其中一个“添加”到一个字符串,其中包含您以粗体显示的语句:templist[curRow]=templist[curRow] + each_char(即此赋值的右侧评估为None + each_char)。

你不能在Python中添加字符串和None,因此错误。


0
投票
string = 'PAHNAPLSIIGYIR'
string = list(string)
rows = []

def make_output(string, num_rows):
    i = 0
    while i < num_rows:
        if i%2 == 0:
            a = []
            while len(a) < 4:
                if len(string)==0:
                    break
                a.append(string.pop(0)) 
            rows.append(a)
        if i%2 != 0:
            a = []
            while len(a) < 7:
                a.append(string.pop(0)) 
            rows.append(a)
        i += 1

    for i in range(len(rows)):
        if i%2 == 0:
            print('   '.join(rows[i]))
        if i%2 != 0:
            print(' '.join(rows[i]))

make_output(string,  3)  

你可以使用这样的函数,在那里你指定偶数和奇数行的长度,然后你可以从你的字符串中pop。然后你可以只有print偶数和奇数行与适当的间距。

(xenial)vash@localhost:~/python/AtBS$ python3.7 solve.py
P   A   H   N
A P L S I I G
Y   I   R

(xenial)vash@localhost:~/python/AtBS$ python3.7 solve.py
M   M   *   H
Y A E S V S *
N   I   A
© www.soinside.com 2019 - 2024. All rights reserved.