String Methods

Module: M3-R5: Python Programming

Chapter: Functions

🔹 Introduction

Python allows flexible operations on strings such as slicing, membership testing, and pattern matching using built-in syntax and functions.

🔹 String Slicing

Slicing extracts a part of the string using the syntax string[start:end:step].

🔹 Example 1
text = 'PythonProgramming'
print(text[0:6])

Output:

Python
🔹 Example 2
text = 'PythonProgramming'
print(text[6:])

Output:

Programming
🔹 Example 3
text = 'PythonProgramming'
print(text[:6])

Output:

Python
🔹 Example 4
text = 'PythonProgramming'
print(text[0:15:2])

Output:

PtoPormig
🔹 Membership Operators

Check whether a substring exists in a string using in and not in.

🔹 Example 1
text = 'Python'
print('P' in text)

Output:

True
🔹 Example 2
text = 'Python'
print('z' in text)

Output:

False
🔹 Example 3
text = 'Python'
print('y' not in text)

Output:

False
🔹 Pattern Matching (Using Regular Expressions)

Python’s re module allows pattern matching in strings.

🔹 Example 1
import re
text = 'Python 123'
pattern = '\d+'
print(re.findall(pattern,text))

Output:

['123']
🔹 Example 2
import re
text = 'Python'
pattern = 'P.*n'
print(re.findall(pattern,text))

Output:

['Python']
🔹 Example 3
import re
text = 'abc123xyz'
pattern = '[a-z]+'
print(re.findall(pattern,text))

Output:

['abc', 'xyz']
✅ Summary
  • Slicing extracts substrings using start, end, and step indexes.
  • Membership operators check for the presence or absence of substrings.
  • Pattern matching allows searching strings using regular expressions.
  • Combine these techniques for powerful string manipulation.
Quick Links