Module: M3-R5: Python Programming
Chapter: Functions
Python allows flexible operations on strings such as slicing, membership testing, and pattern matching using built-in syntax and functions.
Slicing extracts a part of the string using the syntax string[start:end:step].
text = 'PythonProgramming'
print(text[0:6])Output:
Pythontext = 'PythonProgramming'
print(text[6:])Output:
Programming
text = 'PythonProgramming'
print(text[:6])Output:
Pythontext = 'PythonProgramming'
print(text[0:15:2])Output:
PtoPormig
Check whether a substring exists in a string using in and not in.
text = 'Python'
print('P' in text)Output:
Truetext = 'Python'
print('z' in text)Output:
False
text = 'Python'
print('y' not in text)Output:
False
Python’s re module allows pattern matching in strings.
import re
text = 'Python 123'
pattern = '\d+'
print(re.findall(pattern,text))Output:
['123']import re
text = 'Python'
pattern = 'P.*n'
print(re.findall(pattern,text))Output:
['Python']
import re
text = 'abc123xyz'
pattern = '[a-z]+'
print(re.findall(pattern,text))Output:
['abc', 'xyz']