You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python打印含字符串与整数的列表,需保留整数类型以复用

Solution for Printing Your List While Preserving Integer Types

Hey there! No worries at all—let's get this sorted out for you. The key here is that you want to print the list elements as strings without modifying the original list (so those integers stay intact for your later code). Here's how to do it:

First, keep your original list exactly as it is—we don't need to change anything about it, which means the integer values will remain as int type for your follow-up operations:

myList = []
myList.append(['James', 'Herbert', 23])
myList.append(['John', 'Doe', 10])
myList.append(['Phillip', 'Andrews', 45])

Then, to print the content in your desired format, we'll loop through each sublist, convert every element to a string temporarily, join them with spaces, and print the result:

# Loop through each sublist in your main list
for person in myList:
    # Convert each item to a string, then join with spaces and print
    print(' '.join(str(item) for item in person))

What this does:

  • str(item): Takes any element (whether it's a string like "James" or an integer like 23) and turns it into a string version. This is temporary—your original list still has the integer 23, not the string "23".
  • ' '.join(...): Takes all those string elements and glues them together with a single space between each one, creating a line like "James Herbert 23".
  • The loop goes through each sublist (each person's info) and prints one line at a time, which matches your desired output exactly.

Verify the integers are still intact:

If you want to double-check that the original list hasn't changed, you can run this line:

# Check the type of the first person's age
print(type(myList[0][2]))  # Will output <class 'int'>

This confirms the integer is still there for you to use in later code (like doing math operations, comparisons, etc.).

Alternative: Print all lines at once

If you prefer to generate the entire output string first and print it in one go, you can do this:

output = '\n'.join(' '.join(str(item) for item in sublist) for sublist in myList)
print(output)

This does the same thing as the loop, but creates one big string with newline characters between each line, then prints it all at once.

Hope this makes sense—happy coding!

内容的提问来源于stack exchange,提问作者Jasotufy2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:33