-2

How does this line of code work? Google searches on individual characters don't work well.

re.sub(r'(.*>.*/.*)%s(_R[12].*)' % sample.group(1), r'\1%s\2' % sample_name[1], line)

What I don't understand:

  • "% sample.group(1)" .... what is % doing?
  • '\1%s\2' %
  • %s

What I understand:

  • re.sub(x,y,z) will substitute x for y in string z
  • r is for raw (don't mess with /)
  • arrays & indexes
  • _R[12].* matches "_R" and a 1 or 2 followed by random characters.
  • line (it's a string)

Thanks!

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Jon17
  • 73
  • 6
  • https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting `%` is the printf style formatting. Basically, it construct regex and replacement string with data from a previous step. – nhahtdh Dec 19 '19 at 06:06

1 Answers1

2

The % string operator is used for string interpolation/formatting. Think sprintf or String.format:

r'(.*>.*/.*)%s(_R[12].*)' % sample.group(1)

Equals

r'(.*>.*/.*)' + sample.group(1) + r'(_R[12].*)'

Specifically, the s operator (i.e., %s) is defined as:

String (converts any Python object using str()).

.format is the modern way to go, though.

jensgram
  • 31,109
  • 6
  • 81
  • 98