Python में String Slicing
string[start:stop]
string[start:stop:step]
string[::-1]
बेसिक Slicing
Slicing string[start:end] का इस्तेमाल करके किसी string का हिस्सा निकालता है -- start पर मौजूद character शामिल होता है, लेकिन end पर मौजूद character नहीं -- यह एक detail है जो कई beginners को confuse करता है जो एक inclusive range की उम्मीद करते हैं।
उदाहरण: Basic Slicing
text = "Hello"
print(text[1:4])
Indices को छोड़ना
start को छोड़ना Python को slice की शुरुआत index 0 से करने को कहता है, और end को छोड़ना उसे string के आख़िरी character तक slice करने को कहता है -- text[:5] और text[5:] दोनों "शुरू से" और "अंत तक" के लिए common shorthand हैं।
उदाहरण: Omitting Indices
text = "Hello"
print(text[:3]) # start omitted, so it begins at index 0
print(text[3:]) # end omitted, so it goes to the last character
Step Slicing
तीसरी value जोड़ना -- string[start:end:step] -- Python को बताता है कि जो character रखा जाए उसके बीच कितने characters skip करने हैं; text[::2] पूरी string में से हर दूसरा character उठाता है।
उदाहरण: Step Slicing
text = "abcdefgh"
print(text[::2])
Negative Slicing
Negative indices string के अंत से पीछे की ओर गिनते हैं, तो text[-3:] string की कुल length चाहे जो भी हो आख़िरी तीन characters उठा लेता है -- यह तब काम आता है जब आपको पहले से पता न हो कि string exactly कितनी लंबी है।
उदाहरण: Negative Slicing
text = "Hello World"
print(text[-3:])
String को Reverse करना
एक negative step को omitted start और end indices के साथ जोड़ना -- text[::-1] -- पूरी string को एक ही expression में reverse कर देता है, क्योंकि यह Python को string को अंत से शुरुआत तक पीछे की ओर चलने को कहता है।
उदाहरण: Reversing a String
text = "Hello"
print(text[::-1])
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: