String Capitalize करना
तरीका 1: capitalize() Method (First Word Only)
यदि आप केवल String के First Word के First Letter को Capitalize करना चाहते हैं, तो String Class के capitalize Method का उपयोग करें।
>>> s = "my name" >>> s.capitalize() 'My name'
तरीका 2: Manual Slicing
>>> s = "my name" >>> s = s[:1].upper() + s[1:] 'My name'
तरीका 3: title() Method (प्रत्येक Word Capitalize)
यदि आप String के प्रत्येक Word को Capitalize करना चाहते हैं, तो String Class के title Method का उपयोग करें।
>>> s = "my name" >>> s.title() 'My Name'
Comparison:
| Method | Input | Output |
|---|---|---|
capitalize() |
"hello world" | "Hello world" |
title() |
"hello world" | "Hello World" |
upper() |
"hello world" | "HELLO WORLD" |
lower() |
"HELLO WORLD" | "hello world" |
swapcase() |
"Hello World" | "hELLO wORLD" |
Edge Cases with title():
>>> "they're friends".title()
"They'Re Friends" # Apostrophe के बाद भी Capitalize हो जाता है
# Better: str.capwords()
import string
string.capwords("they're friends")
"They're Friends"