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

如何抓取整数类型数据并将指定列表转换为纯整数列表

How to Extract Integer Data from Your List

Hey there! Let's break down how to turn your deneme list into a list of clean integers. Your goal is to take strings with leading newlines and spaces, strip those extra characters, and convert the remaining numeric text to integers—here are a couple of simple, effective ways to do this in Python:

Method 1: List Comprehension (Most Concise)

This is the go-to approach for quick list transformations. We'll use strip() to remove all leading/trailing whitespace (including the \n and spaces) and then convert the cleaned string to an integer with int():

deneme = ['\n 1991', '\n 1993', '\n 2020']
pure_deneme = [int(item.strip()) for item in deneme]

# Check the result and type
print(pure_deneme)          # Output: [1991, 1993, 2020]
print(type(pure_deneme[0])) # Output: <class 'int'>

Method 2: For Loop (Great for Learning)

If you prefer a more explicit step-by-step approach, a basic loop works just as well. It makes each stage of cleaning and conversion clear:

deneme = ['\n 1991', '\n 1993', '\n 2020']
pure_deneme = []

for item in deneme:
    # Remove newlines and leading/trailing spaces
    cleaned_str = item.strip()
    # Convert the cleaned string to an integer
    num = int(cleaned_str)
    # Add the integer to our new list
    pure_deneme.append(num)

print(pure_deneme) # Output: [1991, 1993, 2020]

Why strip()?

Using strip() is better than just replacing \n because it handles any extra spaces (or other whitespace like tabs) automatically. If you only did item.replace('\n', ''), you'd end up with strings like " 1991" which would still cause issues when converting to integers—strip() takes care of all that in one step.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:58:10