Python Strings: Indexing, Slicing, and Essential String Methods

작성자

카테고리:

← 피드로
DEV Community · Tejas Shinkar · 2026-06-18 개발(SW)

As I continue learning Python for Cloud, DevOps, and Automation, I spent some time understanding strings in detail. Strings look simple initially, but Python provides a lot of powerful operations that become useful when working with logs, configuration files, API responses, and automation scripts.

What is a String?

A string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes.

Examples:

"Python"

'DevOps'

"""Multi-line text"""

Key Notes

  • Strings are ordered collections of characters.
  • Strings are immutable.
  • Every character has an index position.

String Indexing

Indexing allows access to individual characters.

text = "DevOps"

print(text[0])
print(text[3])
print(text[-1])

Enter fullscreen mode Exit fullscreen mode

Index Positions

Character D e v O p s Index 0 1 2 3 4 5 Negative Index -6 -5 -4 -3 -2 -1

Examples:

text[0]'D'

text[3]'O'

text[-1]'s'

Key Note

Positive indexing starts from left to right.

Negative indexing starts from right to left.

String Slicing

Slicing extracts a portion of a string.

Syntax

string[start:stop:step]

  • Start is included.
  • Stop is excluded.
  • Step is optional.

Examples:

"DevOps"[0:3]'Dev'

"DevOps"[1:4]'evO'

"DevOps"[:3]'Dev'

"DevOps"[3:]'Ops'

Using Step Value

Every nth character can be extracted using step.

Examples:

"DevOps"[::2]'Dvp'

"DevOps"[::3]'DO'

Reversing a String

One of the most useful slicing tricks:

"DevOps"[::-1]'spOveD'

Why It Matters

This technique is commonly used in interview questions and palindrome checks.

Palindrome Check

A palindrome reads the same forward and backward.

word = "madam"

if word == word[::-1]:
    print("Palindrome")

Enter fullscreen mode Exit fullscreen mode

Examples:

madam

racecar

level

String Concatenation

Concatenation joins strings together.

Examples:

"Hello" + "World"'HelloWorld'

"AWS" + " DevOps"'AWS DevOps'

String Repetition

The * operator repeats a string multiple times.

Examples:

"Python" * 3

Result:

PythonPythonPython

Finding String Length

The len() function returns the total number of characters.

Examples:

len("Python")6

len("DevOps Engineer")15

Useful String Methods

capitalize()

Converts the first character to uppercase.

Examples:

"python".capitalize()'Python'

title()

Capitalizes the first character of every word.

Examples:

"this is python".title()

Result:

'This Is Python'

lower()

Converts all characters to lowercase.

Examples:

"PyThOn".lower()

Result:

'python'

upper()

Converts all characters to uppercase.

Examples:

"PyThOn".upper()

Result:

'PYTHON'

swapcase()

Reverses character casing.

Examples:

"This IS Python".swapcase()

Result:

'tHIS is pYTHON'

count()

Returns the number of occurrences of a substring.

Examples:

"Python".count("o")1

"DevOps DevOps".count("DevOps")2

Useful Feature

Count can search within a specific range.

Example:

text.count("e", 10, 35)

find()

Returns the index of the first occurrence.

Examples:

"Python".find("t")2

"Python".find("z")-1

Key Note

Returns -1 if the value is not found.

index()

Works similarly to find().

Examples:

"Python".index("t")2

Difference

find() returns -1 when not found.

index() raises a ValueError.

strip()

Removes unwanted characters from both ends.

Examples:

" Python ".strip()'Python'

"$%Python$%".strip("$%")'Python'

Important

strip() removes matching characters, not exact patterns.

lstrip()

Removes characters only from the left side.

Example:

" Python".lstrip()

rstrip()

Removes characters only from the right side.

Example:

"Python ".rstrip()

split()

Converts a string into a list.

Examples:

"This is Python".split()

Result:

['This', 'is', 'Python']

Custom separator:

"a,b,c,d".split(",")

Result:

['a', 'b', 'c', 'd']

join()

Converts a list back into a string.

Examples:

" ".join(["This", "is", "Python"])

Result:

'This is Python'

Custom separator:

" | ".join(["AWS", "Docker", "Kubernetes"])

Result:

AWS | Docker | Kubernetes

Quick Revision

Operation Example Length len(text) Indexing text[0] Negative Indexing text[-1] Slicing text[1:5] Reverse String text[::-1] Count text.count("a") Find text.find("a") Index text.index("a") Split text.split() Join " ".join(list) Strip text.strip() Uppercase text.upper() Lowercase text.lower()

Final Thoughts

Most beginner examples use simple words, but these operations become extremely useful when working with log files, configuration values, API responses, and text processing tasks. Understanding indexing, slicing, and common string methods makes Python code cleaner and significantly easier to write.

Small concepts like these eventually become the building blocks for larger automation and infrastructure scripts.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다