0% found this document useful (0 votes)
5 views

string methods

This document provides a detailed explanation of Python strings, covering their definition, methods for manipulation (such as case conversion, searching, modifying, and formatting), and slicing techniques. It includes examples for each method and demonstrates string formatting using f-strings, .format(), and the old % formatting method. Additionally, it showcases practical examples that combine these concepts.

Uploaded by

pradeep702661
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

string methods

This document provides a detailed explanation of Python strings, covering their definition, methods for manipulation (such as case conversion, searching, modifying, and formatting), and slicing techniques. It includes examples for each method and demonstrates string formatting using f-strings, .format(), and the old % formatting method. Additionally, it showcases practical examples that combine these concepts.

Uploaded by

pradeep702661
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Strings: Methods, Formatting, and Slicing (Detailed Explanation)

1. Strings in Python
A string in Python is a sequence of characters enclosed within single ('), double
(") or triple (''' or """) quotes.

python

string1 = 'Hello'
string2 = "World"
string3 = '''This is a multi-line string.'''
Strings are immutable, meaning they cannot be changed once created.

2. String Methods
Python provides a variety of built-in methods to manipulate strings.

A. Case Conversion Methods


Method Description
Example
.upper() Converts all characters to uppercase.
"hello".upper() → 'HELLO'
.lower() Converts all characters to lowercase.
"HELLO".lower() → 'hello'
.title() Capitalizes the first letter of every word. "hello
world".title() → 'Hello World'
.capitalize() Capitalizes only the first letter of the string. "hello
world".capitalize() → 'Hello world'
.swapcase() Swaps uppercase letters to lowercase and vice versa.
"Hello".swapcase() → 'hELLO'

B. Searching and Checking Methods


Method Description
Example
.find(sub) Returns the index of the first occurrence of sub or -1 if not found.
"hello".find('e') → 1
.index(sub) Same as .find(), but raises an error if not found.
"hello".index('e') → 1
.startswith(sub) Returns True if the string starts with sub, else False.
"hello".startswith('he') → True
.endswith(sub) Returns True if the string ends with sub, else False.
"hello".endswith('lo') → True
.count(sub) Counts occurrences of sub in the string.
"hello hello".count('l') → 4

C. Modifying and Replacing Methods


Method Description
Example
.replace(old, new) Replaces all occurrences of old with new.
"hello".replace('l', 'x') → 'hexxo'
.strip() Removes whitespace from both ends. " hello
".strip() → 'hello'
.lstrip() Removes whitespace from the left side. " hello
".lstrip() → 'hello '
.rstrip() Removes whitespace from the right side. " hello
".rstrip() → ' hello'

D. Splitting and Joining Methods


Method Description
Example
.split(sep) Splits the string into a list using sep. "hello
world".split() → ['hello', 'world']
.join(iterable) Joins elements of an iterable into a string.
"-".join(['hello', 'world']) → 'hello-world'

E. Character Type Checking Methods


Method Description
Example
.isalnum() Returns True if all characters are alphanumeric.
"hello123".isalnum() → True
.isalpha() Returns True if all characters are letters.
"hello".isalpha() → True
.isdigit() Returns True if all characters are digits.
"123".isdigit() → True
.isspace() Returns True if all characters are spaces. "
".isspace() → True

3. String Formatting
Python provides several ways to format strings.

A. Using f-strings (Python 3.6+)


The most modern and recommended way to format strings.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.

B. Using .format() Method


print("My name is {} and I am {} years old.".format(name, age))
You can also use index-based or keyword-based formatting:
print("My name is {1} and I am {0} years old.".format(age, name))
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))

C. Using % Formatting (Old Method)


print("My name is %s and I am %d years old." % (name, age))

4. String Slicing
Slicing allows extracting specific portions of a string. The syntax is:
string[start:end:step]
start → Index where slicing starts (inclusive).
end → Index where slicing stops (exclusive).
step → Number of steps to take.

A. Basic Slicing
text = "Python"
print(text[0:4]) # 'Pyth'
print(text[:3]) # 'Pyt' (start defaults to 0)
print(text[2:]) # 'thon' (end defaults to last index)

B. Using Negative Indices


print(text[-1]) # 'n' (last character)
print(text[-3:]) # 'hon' (last 3 characters)
print(text[:-2]) # 'Pyth' (all except last 2 characters)

C. Using Step
print(text[::2]) # 'Pto' (every second character)
print(text[::-1]) # 'nohtyP' (reverse the string)
5. Examples Combining Methods, Formatting, and Slicing
quote = "The quick brown fox jumps over the lazy dog"
words = quote.split() # Splitting into words
filtered_words = [word.capitalize() for word in words] # Capitalizing each word
formatted_string = " | ".join(filtered_words) # Joining with a separator
print(formatted_string)
Output:

mathematica
The | Quick | Brown | Fox | Jumps | Over | The | Lazy | Dog

6. Summary
Concept Example
String Methods .upper(), .lower(), .replace(), .split(), .join()
String Formatting f"Hello {name}", "{}".format(value), "%s" % value
String Slicing text[start:end:step], text[::-1] for reversing

You might also like