簡體   English   中英

在 Python 中,如何在列表和字符串之間留出空格?

[英]In Python how do I make a space between a list and string?

我需要在列表(貓的名字)和索引之間放置一個空格。

現在它出來是這樣的:

Pussy0
Pinky1
Fats2

我希望它像這樣打印出來:

Pussy 0
Pinky 1
Fats 2
catNames = []
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) +
      ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
    #print(name)

for i in range(len(catNames)):
    print(catNames[i] + str(i))

只需這樣做:

catNames = []
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) +
      ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
    #print(name)

for i in range(len(catNames)):
    print(catNames[i] + " " + str(i))

盡管使用f-string s 或format總是更好:

catNames = []
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) +
      ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
    #print(name)

for i in range(len(catNames)):
    print(f"{catNames[i]} {str(i)}")

使用f-string s 使代碼更清晰,更易於理解。 在這里查看更多詳細信息。 請注意,f 字符串僅適用於 python 3.6 或更高版本。 如果您的 python 版本低於 3.6,請查看我之前的回答,了解如何在 python 3.6 以下使用 f-strings。

嘗試字符串格式:

catnames = ['Fuzzy', 'Pinky', 'Fats']

for i, cname in enumerate(catnames):
    print('{} {}'.format(cname, str(i)))

我建議為此使用字符串插值:

for i in range(len(catNames)):
    print(f"{catNames[i]} {i}")

我在“Demolution Brother”的幫助下向我展示了如何在字符串后跟索引中編寫列表。

print(str(i),":",catNames[I]) 
  1. 打印 function
  2. 將干擾變成字符串 - (str(
  3. 在 str( 我們現在有干擾 (str(I)
  4. 重要的是使用, 來分隔要放入“:”的字符串。 它必須用雙引號來完成。
  5. 現在在逗號之后,我們可以繼續 catNames[I]) (The List)
  6. 列表項現在在索引之后打印。
  7. 答案 - print(catNames[i], ": ", str(I))

嘗試了其他一些方法:

    #print(str(i),":",catNames[i])
    #print(catNames[i], i, end=' ')
    #print(catNames[i],end=' ' + str(i))

代碼-cat_names

catNames = []
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) +
      ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
    #print(name)

for i in range(len(catNames)):
    print(str(i),":",catNames[i])
    #print(catNames[i], " : ", str(i))

暫無
暫無

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

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