2016-02-11 105 views
2

的字符串中的字符我有一個​​文本字符串,上面寫着:Python的嵌套循環識別文本

1x2xx1x2xx1x2xx1x2xxx 

我需要拆開的文本字符串,如果它是一個數字,我想通過該數字以及其他一些變量與另一個函數一起在畫布上打印正方形。

我寫了下面的代碼:

def process_single_line(a_canvas, line_of_pattern, left, top, size): 
    x = left 
    y = top 

    for char in line_of_pattern: 
     if char.isdigit(): 
      type_of_tile = int(char) 
      draw_tile (a_canvas, type_of_tile, x, y, size) 
     else: 
      x += size 

我遇到的問題是:

  1. 它似乎沒有工作,矩形和形狀draw_tile 應該打印唐不會出現(但draw_tile功能 工作正常,因爲它被多次引用其中 在其中它打印只是完美的程序)
  2. 在循環結束時,我想通過y + = size將y值增加爲 ,以便當NEXT字符串文本通過 函數時,它將移動到NEXT網格線。

預期結果: enter image description here

我得到什麼VS我想獲得:

enter image description here

+0

你'type_of_tile'參數將是一個字符串,因爲你正在服用的字母(即使字母看起來像「1」,「2」等等)。 'draw_tile'函數是否需要字符串或實際數字?試試'int(type_of_tile)'也許? –

+0

請更新您的問題'1x2xx1x2xx1x2xx1x2xxx'的預期輸出,以便我們能夠理解您想要的內容 –

+0

@AustinHastings您是對的,我必須將其更改爲'int'。 – Nume

回答

2

我相信你應該總是增加渲染後的x位置。

試試這個:

def process_single_line(a_canvas, line_of_pattern, left, top, size): 
    x = left 
    y = top 

    for char in line_of_pattern: 
     if char.isdigit(): 
      type_of_tile = int(char) 
      draw_tile (a_canvas, type_of_tile, x, y, size) 

     x += size 
+0

謝謝!這工作完美! – Nume

2

多行的解決方案(如果你沒有的話)

def process_single_line(a_canvas, line_of_pattern, left, top, size): 
    x = left 
    y = top 

    for char in line_of_pattern: 
     if char.isdigit(): 
      type_of_tile = int(char) 
      draw_tile(a_canvas, type_of_tile, x, y, size) 

     x += size 


lines = ['1x2xx1x2xx1x2xx1x2xxx', '3xxxx3xxxx3xxxx3xxxx'] 
for line_num, line in enumerate(lines): 
    process_single_line(canvas, line, 0, size*line_num, size) 
+0

非常感謝您的幫助。 – Nume