简体   繁体   English

如何打印不带逗号的字符串元组

[英]How to print string tuple without commas

I'm new to Python, If i have this tuple我是 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']]

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.使用join()连接列表中的所有字符串。

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: Barmar 的回答可能是 Python 中执行此操作的最有效方法,但为了学习编程逻辑,这里有一个指导您逐步完成该过程的答案:

First of all, in a nested list, usually 2 layers of loops are required (if no helper or built-in functions are used).首先,在嵌套列表中,通常需要 2 层循环(如果没有使用辅助函数或内置函数)。 Hence our first layer of for loop will have a 1D list as an element.因此,我们的第一层 for 循环将有一个一维列表作为元素。

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:由于 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

Hopefully this helps you understand programming concepts and flows better!希望这可以帮助您更好地理解编程概念和流程!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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