Automatically translated.View original post

🔪 Delve into Python Strings: Super Bang Slicing! 🌟

Let's go to Basic Python on Strings! Today we're going to see the technique of cutting text, also called Slicing! It's very simple and useful.

Slicing uses the [start: end] sign to select the part of the String we want:

1.Basic Slicing: Print (b [2: 5])

• It will run from index 2 to before index 5 (index 5 will not be included!)

2.Slice From the Start: Print (b [: 5])

• If we leave the initial index, it starts to cut the first letter.

3.Slice To The End: Print (b [2:])

• If we leave the final index, it will cut from the given index to the last letter of the String.

4.Negative Indexing: Print (b [-5: -2])

• Use negative numbers to start counting from the end of the string! This example draws the character from the 5th position, from the end (-5) to the second position, from the end (-2).

Try to use this technique to handle text messages. It is a lot more convenient! Practice often and will be better by yourself. Fight! 💪💖

# python # data # ai # programmer # learnonlemon8

2025/11/10 Edited to

... Read moreหลายคนทักมาว่า “string python คืออะไร” เลยขอเสริมให้ครบแบบอ่านจบแล้วไปทำโจทย์ต่อได้เลยนะคะ String (สตริง) ใน Python คือ “ข้อความ” ที่อยู่ในเครื่องหมายคำพูด จะใช้ '...' หรือ "..." ก็ได้ เช่น - s = "Hello, World!" - name = 'Dave' สตริงเอาไว้เก็บตัวอักษร ตัวเลข หรือสัญลักษณ์ต่างๆ (ขอแค่เป็นข้อความ) และที่สำคัญคือ String เป็นลำดับของอักขระ (sequence) เลยทำให้เราเข้าถึงทีละตัวด้วย index ได้ค่ะ เช่น s[0] คือ H สิ่งที่คนพลาดบ่อยๆ เวลาเริ่มทำ Slicing 1) index เริ่มที่ 0 คำว่า "Hello, World!" ตัวแรก H คือ index 0 ไม่ใช่ 1 2) end ใน [start:end] “ไม่รวมตัวท้าย” เช่น b[2:5] จะได้ "llo" เพราะหยุดก่อนตำแหน่ง 5 3) เว้น start หรือ end ได้ - b[:5] ได้ "Hello" (เริ่มจากตัวแรก) - b[2:] ได้ "llo, World!" (ไปจนสุดท้าย) 4) Negative Indexing นับจากท้าย -1 คือท้ายสุด และ b[-5:-2] จะได้ "orl" (ช่วงใกล้ท้ายของ "Hello, World!") ขอเสริมอีกนิดให้ใช้งานคล่องขึ้น: Slicing แบบมี step - b[::2] หยิบทุก 2 ตัวอักษร - b[::-1] กลับสตริงจากหลังมาหน้า (เอาไว้เช็ค palindrome หรือกลับข้อความแบบเร็วๆ) อีกคำที่เจอบ่อยใน Google คือ “หารปัดเศษ python” (เผื่อทำงานกับตัวเลขร่วมกับสตริง) - หารแบบปัดเศษลง (floor division): 7 // 2 ได้ 3 - เศษจากการหาร (mod): 7 % 2 ได้ 1 ทริคที่ใช้บ่อยเวลาแปลงผลลัพธ์ไปเป็นข้อความ: - "ผลลัพธ์คือ " + str(7 // 2) หรือใช้ f-string ที่อ่านง่ายกว่า: - f"ผลลัพธ์คือ {7 // 2}" สรุปสั้นๆ: ถ้าเข้าใจว่า String คือข้อความ + รู้กฎ index เริ่มที่ 0 + end ไม่รวมตัวท้าย คุณจะใช้ slicing ได้คล่องมากขึ้นแน่นอนค่ะ ลองฝึกกับ "Hello, World!" ตามตัวอย่าง b[2:5], b[:5], b[2:], b[-5:-2] แล้วค่อยเปลี่ยนเป็นข้อความของตัวเองดูนะคะ

Related posts

My Programming Interest Just Skyrocketed! 🚀
I just discovered something that has made my interest in programming explode to 1000000000000000%! 🤯 🎮 Learning Programming is Like a Game Adventure! From Python, Java, JavaScript, to HTML, there are all kinds of programming languages available, along with systematic topic courses. The learning p
Valder

Valder

2169 likes

Shadow Work Journaling Prompts ✍🏻
Shadow work involves delving into the unconscious aspects of oneself, known as the "shadow," which encompasses hidden emotions, desires, fears, and traits often deemed unacceptable or repressed. It's a psychological process aimed at acknowledging, understanding, and integrating these da
mindofieva

mindofieva

495 likes

Books that left my jaw on the floor
Fair warning, friends: these books are NOT for the faint of heart. They're raw, intense, and full of messy emotions. They delve into darkness, pain, and the messy realities of life. But they also offer glimpses of hope, resilience, and the incredible strength of the human spirit. I've fe
Meredith Jao

Meredith Jao

9797 likes

8 Free Online Certifications to Boost Your Resume
Hi, lemons! In today's competitive job market, having the right certifications can make a significant difference in showcasing your skills and expertise. Online certifications are not only convenient but also cost-effective. Here are six free online certifications that can give your resume a va
Lifestyle Babe

Lifestyle Babe

1212 likes

An overhead shot of feet in fuzzy slippers on a dark rug, with an iPad displaying '1, 2, 3' and a stylus. Pink text overlay reads '3 pass study method,' introducing a study technique.
A hand holds an iPad showing '1 recognize material,' '2 broader understanding,' and '3 tough concepts' on a grid background, detailing the steps of the '3 pass study method.'
A screenshot of an Instagram post by 'medical.morgan' explaining the '3 pass' study method, emphasizing the importance of the third pass for deep understanding and making connections.
How to become an academic weapon in 3 steps 🩷
Hey fellow students of Lemon8! I wanted to share a great new study technique I learned, called the three pass method. I’ve used this as a great way to work through long amounts of content, and organize my thoughts when learning new things. The first pass is simply for recognition, get yo
bea_studies_PA

bea_studies_PA

59 likes

A baked broccoli chicken cheese casserole in a glass dish inside an oven, with melted golden cheese on top. The text 'Broccoli Chicken Cheese Casserole' is overlaid.
Ingredients for broccoli chicken cheese casserole on a counter: shredded cheese, cream of chicken soup, sour cream, mayonnaise, lemon, salt, pepper, cooked chicken, rice, broccoli, and an empty baking dish.
A glass baking dish with a base layer of white rice topped with green broccoli florets. In the background, a bowl holds a creamy cheese and chicken mixture.
Broccoli Chicken Cheese Rice Casserole
2 cups cooked minute rice 3 cups chopped cooked broccoli florets 6 cups diced, cooked, skinless, boneless chicken breasts 1 can (10 oz.) cream of chicken soup 3 cups (10 oz.) shredded cheddar 1 cup sour cream 1/2 cup mayonnaise 1 tbsp. fresh lemon juice 1/2 tsp. kosher salt 1/4tsp. freshl
Sherri Clark Bennett

Sherri Clark Bennett

153 likes

A hand holds two perfume bottles: Lattafa Eclaire and Khadlaj Cream Velvet, both in light brown and beige tones with gold accents. The image has an 'OOTD' overlay with sparkling star graphics, highlighting a gourmand fragrance layering combination.
Vanilla cupcake-For the gourmand girlies🧁🍨🤎
✨Eclaire + Cream Velvet✨ #gourmandfragrance #vanillaperfume #fragranceaddict #scentlayeringcombos #layeringperfume
Navy♡︎ SAHM Scent Diaries✨

Navy♡︎ SAHM Scent Diaries✨

53 likes

october tbr 🍂🪦🤎👻
do we think i can make it through all of these this month?😅 #booktok #bookstagram #readersoflemon8 #october #tbr
✰ ꜱᴋʏᴇ ☾

✰ ꜱᴋʏᴇ ☾

32 likes

A collage featuring Elicia Goguen, a laptop, self-care items, and a checklist for a 30-day glow-up challenge covering sleep, movement, nourishment, self-development, and self-care. The image introduces how to start and maintain a glow-up journey with habit trackers and templates.
Text outlining the first three takeaways for a 30-day glow-up challenge: starting the challenge for personal growth, prioritizing sleep for energy, and incorporating movement for physical well-being.
Text outlining takeaways 4, 5, and 6 for a glow-up challenge: focusing on nourishment over strict diets, committing one hour daily to self-development, and utilizing habit stacking for efficient self-development.
30-day glow up challenge and tips!
Great advice from Elicia on emarking on a 30-day glow up challenge to kickstart personal growth! 1) Starting a 30-day glow up challenge is crucial for personal growth. - Challenges like these can help individuals break out of slumps and establish consistent routines. - Setting specific goals
Elevate Mind

Elevate Mind

8 likes

A hand holds open a Bible journal with handwritten notes and highlights, featuring the text "BIBLE JOURNAL with me! Psalms 38-42" overlaid. A laptop and colorful pens are visible in the background, suggesting a study session.
An open Bible journal displays Psalms 37-38 with highlighted verses and handwritten notes. Key phrases like "faithful ness," "God is my rescue," and "Turn away from evil" are visible, along with a green-painted fingernail pointing to the text.
An open Bible journal shows Psalm 38 with extensive highlighting and handwritten annotations. Notes include "David feels the Weight of conviction," "guilt affects every part of David," and "healing begins with honesty," alongside the biblical text.
Bible Notes 📖 | Psalms 38-42
Bible notes 📖 | Psalms 38–42 These chapters are raw. They’re honest. They’re full of pain, repentance, and hope. Psalm 38 begins in brokenness, and Psalm 42 ends in holy longing. 💔 When David felt the weight of sin, he cried out. 🕊️ When he felt forgotten, he clung to God’s presence. ❤️‍🔥 And
jazz_whit

jazz_whit

224 likes

👀🪴The Science ofWhy Plants BoostYour Mood🪴👀
🪴Incorporating more plant life into your home and routine can dramatically enhance your quality of life. 🪴From improving air quality to boosting your mood, the numerous benefits of plants are backed by science and are accessible to anyone willing to engage with nature. 🪴So, gather your pots, soil
Nature Elegance

Nature Elegance

38 likes

An assortment of colorful fruits like papaya, dragon fruit, pineapple, and oranges, with an overlay stating "3 fruit peels with high nutritional value that you've been throwing away," introducing the topic of beneficial fruit peels.
A graphic detailing the high nutritional value of dragon fruit peel, including its polyphenol and anthocyanin content, and suggesting consumption methods like blending, cold dishes, or making jellies/gummies.
A graphic highlighting the nutritional benefits of watermelon rinds, specifically its high vitamin C and amino acid content, and offering preparation ideas such as cold salads, soups, or as a filling for dumplings.
Trash or Treasure? Fruit Peels!
Did you know that fruit peels pack a nutritional punch even greater than the fruit flesh itself? Do you typically peel your fruits before indulging? Many opt to discard the peel due to its texture or concerns about pesticide residue. However, you might be surprised to learn that these seemingly
Elisa L.

Elisa L.

32 likes

Ready to deepen your relationship and prayer life?
I am actively on the lookout for women who are eager to embark on a transformative journey through "Fervent," a powerful book that guides us in praying strategically. As I seek individuals ready to delve into the depths of prayer with intention and purpose, I invite you to join me on this e
Prospherr

Prospherr

7 likes

A person in a white tank top and gray sweatpants sits on a wooden floor, holding a phone to take a picture, with a sunset visible through a large window. An overlay reads: 'That girl podcasts ✨️ you will love ✨️'.
A podcast page for 'Anything Goes with Emma Chamberlain' is displayed, featuring a black and white cartoon cover image of a person's head and the podcast title. The description highlights its raw, intimate, and entertaining nature.
A podcast page for 'On Purpose with Jay Shetty' shows a cover image of Jay Shetty and the podcast title. The description states the podcast aims to make wisdom go viral through insightful conversations.
That girl podcasts ✨️ you will love ✨️
#lemon8tainment #myplaylist
Emma Taylor

Emma Taylor

23 likes

A laptop displaying motivational quotes, alongside a notebook with a heart diagram and a textbook, on a bed. The image has text overlay "Quotes I LOVE as a pre-nursing student" and "Swipe" with a Lemon8 watermark.
A phone screen showing a book summary app with categories like Self-Growth and Psychology, displaying various book covers. The text reads "10k+ book summaries, personalized for you" with a Lemon8 watermark.
A phone screen displaying an app interface for turning books into personal podcasts. It shows options to choose up to three books, summarize them, and select podcast styles (Dialogue, Female, Male) with a Lemon8 watermark.
Quotes I LOVE as a Pre-nursing Student🩻🩺
If you’re a pre-nursing student like me, you may look courage at times. Quotes are known to give some people that extra BOOST to keep them going. The best thing for students is to stay motivated. Here’s how I found quotes and encouragement! BeFreed is the #1 smart reading app that condenses n
Naomilily

Naomilily

0 likes

Steven king
I’ve had this book on my TBR showed it a few times but now I’m finally able to get into it. I had to take a break from my other book “Haunting of Aderline” so I read a short story and now gonna start this and go back and forth between my two reads. #horrorbooks #stevenking #horror #bookworms
Officalcozyhome

Officalcozyhome

24 likes

Rotel dip
Believe it or not rotelle dip is a healthy choice of eating Rotel dip Rotel(any kind of your choice) Ground beef 1 pound Any sausage of your choice 1/2 pound Velveeta cheese Queso cheese Green onion Parsley 1/2 cream cheese Chips of your choice #rotel #latedinner #healthyrecipes
Jesscookinitup

Jesscookinitup

345 likes

A college campus scene with students walking, overlaid with text 'Freshmen Brainrot to Ivy League vibes' and decorative elements like pink lips and butterflies, promoting a transformation from brainrot to sophisticated vibes.
A phone screen showcasing study apps like Obsidian and Taskheat, and promoting BeFreed as a smart reading app that condenses 10K+ non-fiction books into 10-min skims, 20-min podcasts, or 30-min deep dives.
A phone screen displaying the BeFreed app, allowing users to turn books into personalized podcasts by selecting up to three books like 'Atomic Habits' and choosing podcast styles such as dialogue, female, or male voices.
Freshmen ✨Brainrot✨ to IVY LEAGUE vibes 🌸🤌💋🤧🌷📸
Yes, they’re free-ish and yes, they’ll make you feel smart 😏 📑📚 These apps helped me📚📑 1. Obsidian 🚂 – For serious note-takers who love linking ideas together like a mind map. 2. Taskheat 🔗– Turns your messy to-do list into a visual flowchart. 3. Bearable 🐾– Track mood, energy, habits, and s
ang3lie

ang3lie

2 likes

Humanize your AI generated content
We can humanize our AI generated content by fixing these 4 things #ai #chatgpt #aitoolsforbusiness #aitools
Rider

Rider

26 likes

Quotes that got me through high school 🌸🍋
There’s always a new quote somewhere waiting to be found. I believe everyone has, like soulmates, a quote that belongs to them. Here’s the app where I found mine: BeFreed condenses new release nonfiction into: • 40 min deep dives • 20 min podcast (Change host voice or tone to your liking) •
Naomilily

Naomilily

2 likes

How to Read Hunger Games Series In One Day!
#apprecommendation #hungergames #bookapp
lani 🎀

lani 🎀

1 like

Quotes i live by as a college student ⭐️📣
There are many times throughout college that I think back on quotes.m to help me gain motivation. I soon realized I didn’t have very many quotes that inspire me anymore, so I found some on BeFreed. BeFreed is the #1 smart reading app that condenses new nonfiction into: • 40 min deep dives
Naomilily

Naomilily

4 likes

A deadly delve
#gamenight #ttrpg #miniatures #rpg #tabletopgames
d9games_rpg

d9games_rpg

1 like

Consumer Reporting Agencies
Understanding consumer credit reporting agencies like Equifax, Experian, and TransUnion is crucial. We delve into their role in helping support fair consumer reporting, including accuracy, confidentiality, and the proper use of your information. #CreditReport #ConsumerRights #CreditEducation
Lemon8er

Lemon8er

3 likes

Join at ellenariboutique.org
@
SavvySonya

SavvySonya

0 likes

If you’re thinking about relocating to Rhode Island – here are some of the many reasons so many people have made the move (including many of my wonderful clients 🤍✨🏡) • Ready to begin planning your move to Rhode Island? As a relocation specialist, and top local agent – I would love to connect, educ
Brooke Buckett,RI + MA REALTOR

Brooke Buckett,RI + MA REALTOR

0 likes

Book #86
He is my all time favorite author. I read Cujo when I was nine and have been a fan ever since.
Christina

Christina

6 likes

A rustic wall hanging features a denim pocket filled with colorful pinecone flowers and green checkered ribbon. A dragonfly adorns the wooden plank, and a bow with a 'relax' tag is on the pocket. This craft piece is designed to evoke feelings of love and art.
Love and Art
#crafts #vase #memories
Freyja’ M

Freyja’ M

44 likes

See more