← Back to Python Course | Chapter 1: Basics | Lesson 11 of 14

Python Type Casting

Type casting एक कप से जूस को बोतल में डालने जैसा है: ड्रिंक वही रहती है पर container बदल जाता है। आप एक value जैसे text 5 को number 5 में बदलते हैं ताकि आप उस पर गणित (math) कर सकें।
Syntax
python
int(value)
float(value)
str(value)
bool(value)

int में बदलना

किसी value को int() में लपेटने से वह पूर्ण संख्या बन जाती है, और float का दशमलव हिस्सा round होने के बजाय कट जाता है — int(9.8) का नतीजा 9 है, 10 नहीं।

int(42) जैसी संख्यात्मक string ठीक काम करती है, लेकिन int(abc) ValueError उठाता है क्योंकि parse करने लायक कोई अंकों का क्रम नहीं है।

उदाहरण: Converting to int

python
print(int(9.8))
print(int("42"))

float में बदलना

float() किसी int या संख्यात्मक string को floating-point संख्या में बदल देता है, जो औसत या प्रतिशत जैसी गणनाओं में दशमलव की सटीकता चाहने पर काम आता है। float('3.14') और float(3) दोनों काम करते हैं, लेकिन float(three) उसी तरह विफल होता है जैसे int() गैर-संख्यात्मक text पर होता है।

उदाहरण: Converting to float

python
print(float("3.14"))
print(float(3))

str में बदलना

str() किसी भी value — संख्या, list, boolean — को उसके text रूप में बदल देता है, जो तब ज़रूरी है जब आपको उस value को + operator से किसी संदेश में जोड़ना हो, क्योंकि Python strings और संख्याओं को चुपचाप नहीं मिलाती।

print पहले से values को आपके लिए बदल देता है, लेकिन हाथ से string बनाने के लिए साफ़ str() ज़रूरी है।

उदाहरण: Converting to str

python
age = 30
message = "Age: " + str(age)  # str() converts the int so it can be concatenated
print(message)

bool में बदलना

bool() किसी भी value को Python के truthiness नियमों से True या False में समेट देता है — शून्य, None और खाली containers False बन जाते हैं, और लगभग बाकी सब True।

यह बदलाव if condition के अंदर अपने-आप होता है, जो समझाता है कि if my_list: बिना लंबाई की स्पष्ट तुलना किए क्यों काम करता है।

उदाहरण: Converting to bool

python
print(bool(0))  # 0 is falsy
print(bool([]))  # empty list is falsy
print(bool("hello"))  # non-empty string is truthy

Collections के बीच बदलना

list(), tuple() और set() collection types और अन्य iterables के बीच बदल सकते हैं — set() खासकर list से duplicates हटाने के काम आता है, क्योंकि set में बदलने से दोहराव गिर जाते हैं और वापस list बनाने से सामान्य sequence लौट आता है।

ये बदलाव मूल object को in-place बदलने के बजाय एकदम नया object बनाते हैं।

उदाहरण: Converting Between Collections

python
numbers = [1, 2, 2, 3, 3]
unique = list(set(numbers))  # set() drops duplicates, list() converts back to a list
print(unique)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.