Beginning and End of String in Python Regular Expressions

There are special symbols that denote the beginning '^' or the end of a string '$'. Let's see how they work with examples.

Example

In this example, the search pattern is: replace 'aaa' with '!' only if it is at the beginning of the string:

pythontxt = 'aaa aaa aaa'
res = re.sub('^aaa', '!', txt)

print(res)

Result of code execution:

python'! aaa aaa'

Example

In this example, the search pattern is: replace 'aaa' with '!' only if it is at the end of the string:

pythontxt = 'aaa aaa aaa'
res = re.sub('aaa$', '!', txt)

print(res)

Result of code execution:

python'aaa aaa !'

Example

When the regular expression starts with '^', and ends with '$', then the entire string is checked for compliance with the regular expression.

In the following example, the search pattern is: letter 'a' repeated one or more times, replace the entire string with '!' only it consists of the letters 'a':

pythontxt = 'aaa'
res = re.sub('a+$', '!', txt)

print(res)

Result of code execution:

python'!'

Practical tasks

Задание 1

Given a string:

pythontxt = 'abc def xyz'

Write a regular expression that will find the first substring of letters.

Задание 2

Given a string:

pythontxt = 'abc def xyz'

Write a regular expression that will find the last substring of letters.