Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P2.3 Python मध्ये Data Type कसा बदलायचा (Type Casting)?

By Ravindra Bagale

हे का शिकायचं?

File मधून आलेले आकडे बहुतेक text असतात. गणित करण्याआधी त्यांना number मध्ये बदलावं लागतं.

हे काय आहे?

int(), float(), str() आणि bool() ही functions value चा type बदलतात. Number नसलेला text int() ला दिला तर ValueError येतो.

कसं करायचं?

Step 1. Value चा type तपासा.

Step 2. योग्य function (int, float, str) वापरा.

Step 3. Error आला तर value साफ करा.

उदाहरणं: copy करा आणि चालवा

उदाहरण A: Text ते number

हा code चालवा:

amount_text = "120.50"
amount = float(amount_text)
print(amount + 5)

तुम्हाला दिसणारा output:

125.5

याचा अर्थ: float() ने text चे numbers झाले, आता गणित करता येतं.

उदाहरण B: Message साठी number ते text

हा code चालवा:

visits = 3
message = "Total visits: " + str(visits)
print(message)

तुम्हाला दिसणारा output:

Total visits: 3

याचा अर्थ: Text आणि number थेट जोडता येत नाहीत, म्हणून str() वापरलं.

उदाहरण C: मुद्दाम केलेली error: number नसलेला text

हा code चालवा:

print(int("1,200"))

तुम्हाला दिसणारा output:

ValueError: invalid literal for int() with base 10: '1,200'

याचा अर्थ: "1,200" मध्ये comma आहे, त्यामुळे int() ला तो number वाटत नाही आणि ValueError येतो. आधी comma काढा.