← Back

Home › Hindi › String को int में बदलना Hindi में

String को int में बदलना — int(), float() और साफ करना

🌐 यह page Hindi में है · ValueError: invalid literal का पूरा fix →

int() बनाम float()SafaiBaseError handling

बुनियाद

int() text को integer में बदलता है, float() decimal में। दोनों आसपास की whitespace माफ करते हैं और leading sign स्वीकार करते हैं।

int("42")            # 42
int("  42  ")        # 42   — whitespace ठीक है
int("+42")           # 42
int("-42")           # -42
float("3.5")         # 3.5
float("42")          # 42.0

int(3.9)             # 3    — actual float truncate होता है
round(3.9)           # 4
int("3.5")           # 💥 ValueError — decimal string सीधे नहीं चलता
int(float("3.5"))    # 3    — पहले float, फिर int
int("abc")           # 💥 ValueError: invalid literal for int() with base 10: 'abc'
int("3.5")           # 💥 ValueError: invalid literal for int() with base 10: '3.5'
int("")              # 💥 ValueError: invalid literal for int() with base 10: ''
int("1,299")         # 💥 comma स्वीकार नहीं
int("$50")           # 💥 currency symbol स्वीकार नहीं

input() हमेशा string देता है

यही वो जगह है जहाँ शुरुआत में सबसे ज़्यादा गलतियाँ होती हैं। input() कभी number नहीं देता।

age = input("उम्र: ")        # '25' — string, number नहीं
print(age + 1)               # 💥 TypeError: can only concatenate str

if age > 18:                 # 💥 TypeError: '>' not supported
                             #    between instances of 'str' and 'int'
# ✅ boundary पर convert करो
age = int(input("उम्र: "))
print(age + 1)               # 26

# ✅ गलत input पर दोबारा पूछो
while True:
    raw = input("उम्र: ").strip()
    if raw.isdigit():
        age = int(raw)
        break
    print("सिर्फ number डालें")

# ✅ try/except — बेहतर, क्योंकि -5 भी स्वीकार करता है
while True:
    try:
        age = int(input("उम्र: "))
        break
    except ValueError:
        print("सही number डालें")

isdigit() और try/except में फर्क है: isdigit() negative numbers और "3.5" को मना कर देता है। अगर negative मान्य है तो try/except लिखो।

गंदे text को साफ करना

असली data — CSV, spreadsheet, API — कभी साफ नहीं होता। एक reusable function लिख लो:

def to_int(raw, default=0):
    '''गंदे text से integer निकालो; न मिले तो default.'''
    if raw is None:
        return default
    s = str(raw).strip()
    if not s:
        return default
    for junk in "$€£₹, %_":
        s = s.replace(junk, "")
    parts = s.split()
    if parts:
        s = parts[0]                 # '12 kg' -> '12'
    try:
        return int(float(s))         # '3.9' भी स्वीकार, truncate होगा
    except ValueError:
        return default

to_int("$1,299")        # 1299
to_int("12 kg")         # 12
to_int("  42 ")         # 42
to_int("")              # 0
to_int("abc")           # 0

दो सावधानियाँ। comma हटाना European format (1.299,00) को बिगाड़ देता है — वहाँ पहले s.replace('.', '').replace(',', '.') करो। और default चुपचाप खराब rows छिपा देता है, तो skip किए गए values log करो।

Base — binary, hex, octal

int("1010", 2)       # 10   — binary
int("ff", 16)         # 255  — hexadecimal
int("0xff", 16)       # 255  — 0x prefix भी ठीक
int("17", 8)          # 15   — octal
int("42", 10)         # 42   — दस का आधार, यही default

# उलटी दिशा
bin(10)               # '0b1010'
hex(255)              # '0xff'
oct(15)               # '0o17'
format(255, "b")      # '11111111'  — prefix के बिना
format(255, "#x")     # '0xff'

int("0b1010")         # 💥 — prefix के साथ base देना ज़रूरी है
int("0b1010", 0)      # 10  — base 0 का मतलब prefix से खुद पहचानो

आखिरी line काम की है: base=0 देने पर Python prefix (0x, 0b, 0o) देखकर खुद base पहचान लेता है।

round, truncate और floor

Float से int बनाते वक्त चार अलग नतीजे मिल सकते हैं। फर्क समझ लो:

x = 3.7
int(x)                 # 3   — शून्य की ओर truncate
round(x)               # 4   — नज़दीकी तक round
import math
math.floor(x)          # 3   — नीचे की ओर
math.ceil(x)           # 4   — ऊपर की ओर

x = -3.7
int(x)                 # -3  — शून्य की ओर, यानी ऊपर!
math.floor(x)          # -4  — नीचे की ओर
math.ceil(x)           # -3

round(2.5)             # 2   — banker's rounding, 3 नहीं!
round(3.5)             # 4
round(3.14159, 2)      # 3.14
round(2.5)     # 2  — उम्मीद 3 थी, मिला 2
round(0.5)     # 0
round(1.5)     # 2
# Python 'half to even' करता है — .5 पर नज़दीकी सम संख्या चुनता है

# हमेशा ऊपर round चाहिए तो
math.floor(x + 0.5)     # या decimal module use करो

round(2.5) == 2 सबसे ज़्याका चौंकाने वाला Python तथ्य है। ये bug नहीं है — IEEE 754 का banker's rounding है, जो बार-बार round करने पर bias नहीं बनाता। पर पैसे के हिसाब में अक्सर नहीं चाहिए, तो decimal.Decimal use करो।

CSV पढ़ते वक्त

import csv

rows = []
with open("sales.csv", newline="", encoding="utf-8") as f:
    for n, row in enumerate(csv.DictReader(f), start=2):   # header पहली line
        try:
            row["qty"] = int(row["qty"])
        except ValueError:
            print(f"line {n}: cannot parse {row['qty']!r}")
            row["qty"] = 0
        rows.append(row)

Line number print करना ज़रूरी है। दस हज़ार rows में एक खराब row होगी, और बिना line number के पता नहीं चलेगा कहाँ देखना है। !r लगाने से खाली string और '0' का फर्क साफ दिखता है।

आम गलतियाँ

age = input("Age: ")     # '25'
age + 1                  # TypeError
int("3.5")               # ValueError
int("-5").isdigit()      # AttributeError — int का isdigit नहीं होता
"-5".isdigit()           # False — negative number मना हो जाएगा

🛠️ Practice करो (free, browser में)

पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।

सारे free problems देखो →

अक्सर पूछे जाने वाले सवाल

int() और float() में क्या फर्क है?

int() integer बनाता है और decimal string मना कर देता है — int('3.5') पर ValueError आता है। float() decimal स्वीकार करता है। Decimal text से integer चाहिए तो int(float(x)) लिखो।

input() का नतीजा सीधे जोड़ क्यों नहीं सकता?

क्योंकि input() हमेशा string लौटाता है, चाहे user ने number ही क्यों न टाइप किया हो। '25' + 1 पर TypeError मिलेगा। Boundary पर ही int(input(...)) कर लो।

round(2.5) का जवाब 2 क्यों आता है?

क्योंकि Python banker's rounding करता है — .5 पर नज़दीकी सम संख्या चुनता है, ताकि बार-बार round करने पर bias न बने। हमेशा ऊपर round चाहिए तो math.floor(x + 0.5) लिखो।

'1,299' को कैसे convert करें?

पहले comma हटाओ — int('1,299'.replace(',', '')). Currency symbol भी पहले हटाना पड़ेगा। European format (1.299,00) में अलग तरीका चाहिए, वहाँ पहले dot हटाकर comma को dot बनाओ।

Binary या hex string को int में कैसे बदलें?

int('1010', 2) से 10 और int('ff', 16) से 255 मिलता है। 0x या 0b prefix हो तो वही base दो, या base 0 दो जिससे Python prefix से खुद पहचान ले।

आगे पढ़ो