What percentage sign do Python regular expressions use?

Asked 1 years ago, Updated 1 years ago, 97 views

What does the % part of the code below do?

Affected parts

l_regex=re.compile(r'^%s*'%character[0])
r_regex=re.compile(r'%s*$'%character[0])

whole code

import re

def strip_text(text, *character):
    if character:
        print(character)
        l_regex=re.compile(r'^%s*'%character[0])
        r_regex=re.compile(r'%s*$'%character[0])
    else:
        l_regex=re.compile(r'^\s*')
        r_regex=re.compile(r'\s*$')
    text=l_regex.sub(', text)
    text=r_regex.sub(', text)
    print(text)

strip_text('Remove space characters')
strip_text ('XXXX', 'X' to remove X before and after XXXX)

python regular-expression

2022-09-30 21:35

1 Answers

This replaces the string as a format string. It is a string format in the % format. %s is replaced by a string passed later.

>>'aaa%sbb'%'Ah'
'aaa abbb'
>>'aaa%sbb'%'i'
'aaa nice bbb'

For this code, the format string is used to dynamically create a regular expression for each first character of the given string character[0].

In addition, using % to format strings is now an old way, and there is a new way to format strings using f strings.See "Python's new string format: % symbol, str.format() to string complement".


2022-09-30 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.