⊗pyPmREWB 48 of 128 menu

Word Boundaries in Python Regular Expressions

The '\\b' command references a word boundary, while '\B' or '\\B' do not reference a boundary. Note that Python strictly uses double-slash escaping for word boundaries, while other commands allow a single slash. Let's see how these commands work with examples.

Example

Let's wrap each word in the symbol '!':

txt = 'aaa aaa aaa' print(re.sub('\\b', '!', txt))

Result of code execution:

'!aaa! !aaa! !aaa!'

Example

Let's add the symbol '!' in the spaces between the letters:

txt = 'aaa aaa aaa' print(re.sub('\\B', '!', txt))

Result of code execution:

'a!a!a a!a!a a!a!a'

Practical tasks

Given a string:

txt = 'abc def xyz'

Write a regular expression that will transform this line into the following:

'#abc# #def# #xyz#'

Given a string:

txt = 'abc def xyz'

Write a regular expression that will transform this line into the following:

'a+b+c d+e+f x+y+z'
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline