DEV Community

yugalakshmi
yugalakshmi

Posted on Edited on

Python String Method

What is a Python String?

A string (str) is an ordered sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' for multi-line text).
• Versatile Characters: Strings can hold letters, numbers, symbols, and spaces.
• No Separate char Type: Unlike C, C++, or Java, Python does not have a separate char data type. A single letter like 'A' is simply a string with a length of 1.

Positive & Negative Indexing

Because strings are ordered sequences, every character has an index number:
• Positive Indexing: Starts at 0 from the left (0, 1, 2...).
• Negative Indexing: Starts at -1 from the right (-1, -2, -3...).

 word = "PYTHON"

print(word[0])  
  Output: P (first character)

print(word[-1])  
 Output: N (last character)
Enter fullscreen mode Exit fullscreen mode

Immutability & How Memory Works

In Python, strings are immutable, meaning their contents cannot be changed after they are created.
Whenever you modify a string, Python leaves the original memory untouched and creates a new string in a new memory location.
• Memory Address (id() & hex()): Every object in Python has a unique identity (id()). Using hex(id(obj)) shows its hexadecimal memory address.
• Hash Value (hash()): The hash() function generates a fixed integer used for fast lookups in dictionaries and sets. Since strings never change, their hash value stays constant.
• Garbage Collection (gc): Unused objects left behind in memory are called "garbage." Python automatically reclaims this memory through Garbage Collection, which you can inspect or control using the built-in gc module.

String Slicing

Slicing lets you extract a substring by specifying a start index, stop index, and step size.
Syntax:
python
string_name[start:stop:step]

• start: Where the slice starts (inclusive). Defaults to 0.
• stop: Where the slice stops (exclusive—stops at stop - 1). Defaults to the end of the string.
• step: How many characters to move forward (or backward if negative). Defaults to 1.

Diagram illustrating Python string indexing and slicing using the text PYTHON PROGRAMMING, showing positive and negative indices with slicing examples

text = "PYTHON PROGRAMMING"

print(text[:])
print(text[0:6])
print(text[:6])
print(text[7:])
print(text[::2])
print(text[7:14])
print(text[::-1])

Enter fullscreen mode Exit fullscreen mode

Output

PYTHON PROGRAMMING
PYTHON
PYTHON
PROGRAMMING
PTO PORMIG
PROGRAM
GNIMMARGORP NOHTYP

Essential Python String Methods

Python comes packed with built-in methods to clean, format, and transform strings. Because strings are immutable, every method returns a new string.

Cleaning Whitespace

• .strip(): Removes spaces from both ends (" hello ".strip() → "hello").
• .lstrip(): Removes spaces from the front/left (" hello".lstrip() → "hello").
• .rstrip(): Removes spaces (or specified trailing characters) from the back/right while leaving the front untouched (" hello ".rstrip() → " hello").

Changing Case

• .lower() / .upper(): Converts text to all lowercase or uppercase.
• .title(): Capitalizes the first letter of every word ("python strings".title() → "Python Strings").

Splitting & Joining (Converting Between Lists and Strings)

• .split(sep): Splits a string into a list ("a,b,c".split(",") → ['a', 'b', 'c']).
• .join(list): Combines a list into a single string (" ".join(["Python", "is", "fun"]) → "Python is fun").

Searching & Replacing

• .replace(old, new): Replaces a substring ("I love Java".replace("Java", "Python") → "I love Python").
• .find(sub): Returns the starting index of a substring, or -1 if not found.

raw_text = "   python programming   "

print(raw_text.strip())
print(raw_text.rstrip())
print(raw_text.strip().title())
print(raw_text.strip().replace("python", "java"))
print("-".join(["Python", "is", "awesome"]))

Enter fullscreen mode Exit fullscreen mode
 Output


python programming
   python programming
Python Programming
java programming
Python-is-awesome

Enter fullscreen mode Exit fullscreen mode

Top comments (0)