简体   繁体   中英

How to print string tuple without commas

I'm new to Python, If i have this tuple

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']]

How can I print it out so that it reads without any commas and without spaces? And new lines after each row?

pcndthg
waxoaxf
otwgdrk
ljpibet
fvltown

Use join() to concatenate all the strings in a list.

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

or change the default separator to an empty string.

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

Barmar's answer is likely the most efficient possible way to do this in Python, but for the sake of learning programming logic, here is an answer that guides you through the process step by step:

First of all, in a nested list, usually 2 layers of loops are required (if no helper or built-in functions are used). Hence our first layer of for loop will have a 1D list as an element.

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

So within this loop, we attempt to loop through each alphabet in row:

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

Since the built-in print() function in Python will move to the next line by default, we try to use a string variable to "stack" all characters before outputting it:

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

Hopefully this helps you understand programming concepts and flows better!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM