Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

python - getting an issue when adding strings?

I am having issues with the second to last 'elif' statement, I am getting the concatenation error with str and integers-> any explanation to why this is? My understanding is that I am adding a string "R" to the empty string next_row.

Specifically the error is "can only concatenate str (not "int") to str"

  def triangle(row):
     next_row = ''

     for i in row:
         if i == 'G' and (i + 1) == 'B':
             next_row += 'R'

         elif i == 'G' and (i + 1) == 'R':
             next_row += 'B'

         elif i == 'R' and (i + 1) == 'B':
             next_row += 'G'

         elif i == 'R' and (i + 1) == 'G':
             next_row += 'B'

         elif i == 'B' and (i + 1) == 'G':
             next_row += 'R'

         elif i == 'B' and (i + 1) == 'R':
             next_row += 'G'

     print(type(next_row))
     return None

 triangle("BRGGBRG")
question from:https://stackoverflow.com/questions/65873000/getting-an-issue-when-adding-strings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your issue is (i + 1). Python does not know what to do with that.
Python cannot resolve 'A' + 1.

I presume that when you say (i + 1) you are trying to look at the next iteration of row.

Instead, iterate over range(0, len(row)). Use row[i] to see the current value, and row[i + 1] to look at the next one.

def triangle(row):
    next_row = ''

    for i in range(0, len(row)):
        if row[i] == 'G' and row[i + 1] == 'B':
            next_row += 'R'

        elif row[i] == 'G' and row[i + 1] == 'R':
            next_row += 'B'

        elif row[i] == 'R' and row[i + 1] == 'B':
            next_row += 'G'

        elif row[i] == 'R' and row[i + 1] == 'G':
            next_row += 'B'

        elif row[i] == 'B' and row[i + 1] == 'G':
            next_row += 'R'

        elif row[i] == 'B' and row[i + 1] == 'R':
            next_row += 'G'

    print(type(next_row))
    return None

triangle("BRGGBRG ")

Note that using row[i + 1] on the last value will result in a run time error, since there won't be a next value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...