my_string = '#This will display the number of rows and columns in the dataframe.\n\nprint(f"Number of columns: {$[DATASET].shape[1]}")\nprint(f"Number of rows: {$[DATASET].shape[0]}")\n'
param_list = ['df1']
I'm currently using regex to replace all values in the string that start with dollar signs and end up with closing brackets such as $[DATASET] with whatever is in my param_list. My regex works as I've tested it using findall, i'm just having issues with replacing the values. This is my regex code:
re.sub(r'\$\[[^\]] ?\]', '{}',my_string).format(*param_list)
and I keep getting this issue:
Single '}' encountered in format string'.
The reason i'm unpacking the list is because sometimes param_list will have multiple items
CodePudding user response:
You need to double up on the curly braces before running format on it, because format will replace double {{
with a single {
. It needs these 'escaped' because it considers the curly brace an escape character to know where to start a replacement.
Here's an example that works with your example data:
import re
my_string = '#This will display the number of rows and columns in the dataframe.\n\nprint(f"Number of columns: {$[DATASET].shape[1]}")\nprint(f"Number of rows: {$[DATASET].shape[0]}")\n'
param_list = ['test1', 'test2']
s = re.sub('{', '{{', re.sub('}', '}}', my_string))
s = re.sub(r'\$\[[^\]] ?\]', '{}', s).format(*param_list)
print(s)
Result:
#This will display the number of rows and columns in the dataframe.
print(f"Number of columns: {test1.shape[1]}")
print(f"Number of rows: {test2.shape[0]}")