簡體   English   中英

如何打印不帶逗號的字符串元組

[英]How to print string tuple without commas

我是 Python 的新手,如果我有這個元組

testGrid = [['p','c','n','d','t','h','g'],
    ['w','a','x','o','a','x','f'],
    ['o','t','w','g','d','r','k'],
    ['l','j','p','i','b','e','t'],
    ['f','v','l','t','o','w','n']]

我怎樣才能把它打印出來,讓它讀起來沒有任何逗號和空格? 每行之后換行?

pcndthg
waxoaxf
otwgdrk
ljpibet
fvltown

使用join()連接列表中的所有字符串。

for row in testGrid:
    print(''.join(row))

或將默認分隔符更改為空字符串。

for row in testGrid:
    print(*row, sep='')

Barmar 的回答可能是 Python 中執行此操作的最有效方法,但為了學習編程邏輯,這里有一個指導您逐步完成該過程的答案:

首先,在嵌套列表中,通常需要 2 層循環(如果沒有使用輔助函數或內置函數)。 因此,我們的第一層 for 循環將有一個一維列表作為元素。

for row in testGrid:
    print("something")
    # row = ['p','c','n','d','t','h','g']

所以在這個循環中,我們嘗試遍歷行中的每個字母表:

for char in row:
    print(char)
    # char = 'p'

由於 Python 中內置的print() function 默認會移到下一行,因此我們嘗試使用一個字符串變量將所有字符“堆疊”起來再輸出:

for row in testGrid:

    # loop content applies to each row

    # define string variable
    vocab = ""

    for char in row:
        # string concatenation (piecing 2 strings together)
        vocab = vocab + char

    # vocab now contains the entire row, pieced into one string
    print(vocab)

    # remark: usually in other programming languages, moving cursor to the next line requires extra coding
    # in Python it is not required but it is still recommended to keep this in mind

希望這可以幫助您更好地理解編程概念和流程!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM