【问题标题】:How to print string tuple without commas如何打印不带逗号的字符串元组
【发布时间】:2021-10-06 21:45:31
【问题描述】:

我是 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

【问题讨论】:

    标签: python string function tuples


    【解决方案1】:

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

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

    或将默认分隔符更改为空字符串。

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

    【讨论】:

      【解决方案2】:

      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() 函数默认会移动到下一行,所以我们尝试使用字符串变量在输出之前“堆叠”所有字符:

      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
      

      希望这可以帮助您更好地理解编程概念和流程!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 2022-10-13
        • 1970-01-01
        • 2013-02-06
        • 1970-01-01
        • 2021-06-18
        相关资源
        最近更新 更多