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

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

P3.3 Python String Methods: strip, lower, upper, replace, split

By Ravindra Bagale

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

Data मधला text गोंधळलेला असतो: जास्तीच्या spaces, वेगवेगळं case, ₹ आणि commas. Methods ने तो एका line मध्ये साफ होतो.

हे काय आहे?

strip() कडेच्या spaces काढतो, lower()/upper()/title() case बदलतात, replace() text बदलतो आणि split() text चे तुकडे करून list देतो. Methods मूळ string बदलत नाहीत, नवीन देतात.

कसं करायचं?

Step 1. आधी strip() करा.

Step 2. मग case एकसारखा करा.

Step 3. नको असलेली चिन्हं replace() ने काढा.

Step 4. गरज असेल तर split() करा.

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

उदाहरण A: Spaces आणि case साफ करा

हा code चालवा:

city = "   CHENNAI  "
clean = city.strip().title()
print(clean)

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

Chennai

याचा अर्थ: strip() ने कडेच्या spaces गेल्या आणि title() ने नाव नीट case मध्ये आलं.

उदाहरण B: पैशांची value साफ करा

हा code चालवा:

raw = "R 12,450.00"
num = float(raw.replace("R", "").replace(",", "").strip())
print(num)

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

12450.0

याचा अर्थ: ₹ आणि commas काढून float() केल्यावर number मिळाला.

उदाहरण C: पूर्ण नाव आणि email split करा

हा code चालवा:

full = "Sofia Garcia Lopez"
parts = full.split(" ")
print(parts)
print(parts[0])
email = "sofia@example.com"
print(email.split("@")[1])

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

['Sofia', 'Garcia', 'Lopez']
Sofia
example.com

याचा अर्थ: split() ने list मिळते. Email "@" वर कापलं की username आणि domain वेगळे होतात.

उदाहरण D: List परत text मध्ये जोडा

हा code चालवा:

tags = ["organic", "fresh", "local"]
print(", ".join(tags))

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

organic, fresh, local

याचा अर्थ: ", ".join(list) सगळे items एका text मध्ये जोडतो.