Python Type Casting
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
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
print(float("3.14"))
print(float(3))
str में बदलना
str() किसी भी value — संख्या, list, boolean — को उसके text रूप में बदल देता है, जो तब ज़रूरी है जब आपको उस value को + operator से किसी संदेश में जोड़ना हो, क्योंकि Python strings और संख्याओं को चुपचाप नहीं मिलाती।
print पहले से values को आपके लिए बदल देता है, लेकिन हाथ से string बनाने के लिए साफ़ str() ज़रूरी है।
उदाहरण: Converting to str
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
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
numbers = [1, 2, 2, 3, 3]
unique = list(set(numbers)) # set() drops duplicates, list() converts back to a list
print(unique)
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: