![](/img/trans.png)
[英]How do I remove a space between an integer variable and a string in Python 3?
[英]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])
嘗試了其他一些方法:
#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.