Python में data को केवल numbers के रूप में ही नहीं, बल्कि text के रूप में भी store किया जाता है।
ऐसे text data को String कहा जाता है।
Strings का उपयोग words, sentences, names, messages और किसी भी textual information को represent करने के लिए किया जाता है।
यह programming का एक बहुत महत्वपूर्ण हिस्सा है, क्योंकि लगभग हर program में text handling की जरूरत होती है।
String क्या होता है
String characters (letters, digits, symbols) का एक sequence होता है, जिसे quotes के अंदर लिखा जाता है।
Python में string को तीन तरीकों से define किया जा सकता है:
- Single quotes (‘ ‘)
- Double quotes (” “)
- Triple quotes (”’ ”’ या “”” “””)
String बनाने के उदाहरण
name = "Rahul"
city = 'Delhi'
message = """Welcome to Python"""
print(name)
print(city)
print(message)
String Indexing
String के हर character का एक index होता है।
Index 0 से शुरू होता है।
text = "Python"
print(text[0])
print(text[1])
Output
P
y
Explanation
यहाँ text[0] पहला character है और text[1] दूसरा character है।
Negative Indexing
Python में string को पीछे से भी access किया जा सकता है।
text = "Python"
print(text[-1])
Output
n
Explanation-1 का मतलब last character होता है।
String Slicing
Slicing का उपयोग string का एक हिस्सा निकालने के लिए किया जाता है।
text = "Python"
print(text[0:3])
Output
Pyt
Explanation
यह index 0 से 2 तक characters को return करता है।
String Operations
1. Concatenation (जोड़ना)
a = "Hello"
b = "World"
print(a + " " + b)
Output
Hello World
2. Repetition
text = "Hi "
print(text * 3)
Output
Hi Hi Hi
String Functions (Methods)
Python में string के साथ कई useful functions होते हैं:
text = "python"
print(text.upper())
print(text.lower())
print(len(text))
Output
PYTHON
python
6
Explanation
upper()→ uppercase करता हैlower()→ lowercase करता हैlen()→ length बताता है
Real-life Example: Greeting message
name = input("Enter your name: ")
print("Hello " + name)
Explanation
यह program user का नाम लेकर greeting message print करता है।
Real-life Example: Email check
email = input("Enter email: ")if "@" in email:
print("Valid Email")
else:
print("Invalid Email")
Explanation
यह example simple validation दिखाता है कि email में “@” है या नहीं।
Escape Characters
कुछ special characters को represent करने के लिए escape characters use होते हैं:
print("Hello\nWorld")
print("He said \"Hello\"")
Output
Hello
World
He said "Hello"
Common mistakes
- quotes सही use न करना
- indexing में गलत position लेना
- string और number को directly जोड़ना
Simple complete program
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Name:", name)
print("Age:", age)
इस topic की मुख्य बात
Strings Python में text data को store और process करने के लिए उपयोग किए जाते हैं।
इस topic में student यह सीखता है:
- string क्या है
- indexing और slicing कैसे काम करती है
- string operations
- useful functions
- real-life use