← Back to Python Course | Chapter 5: Strings | Lesson 3 of 6

Python में String Slicing

Slicing किसी string का एक टुकड़ा काटना है, जैसे किसी ब्रेड की loaf से एक slice काटना। आप बताते हैं कि कहाँ से शुरू करना है और कहाँ रुकना है।
Syntax
python
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

python
text = "Hello"
print(text[1:4])

Indices को छोड़ना

start को छोड़ना Python को slice की शुरुआत index 0 से करने को कहता है, और end को छोड़ना उसे string के आख़िरी character तक slice करने को कहता है -- text[:5] और text[5:] दोनों "शुरू से" और "अंत तक" के लिए common shorthand हैं।

उदाहरण: Omitting Indices

python
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

python
text = "abcdefgh"
print(text[::2])

Negative Slicing

Negative indices string के अंत से पीछे की ओर गिनते हैं, तो text[-3:] string की कुल length चाहे जो भी हो आख़िरी तीन characters उठा लेता है -- यह तब काम आता है जब आपको पहले से पता न हो कि string exactly कितनी लंबी है।

उदाहरण: Negative Slicing

python
text = "Hello World"
print(text[-3:])

String को Reverse करना

एक negative step को omitted start और end indices के साथ जोड़ना -- text[::-1] -- पूरी string को एक ही expression में reverse कर देता है, क्योंकि यह Python को string को अंत से शुरुआत तक पीछे की ओर चलने को कहता है।

उदाहरण: Reversing a String

python
text = "Hello"
print(text[::-1])
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.