Search code examples
pythonpython-3.xstringstring-formattingf-string

Constructing a long Python string using variables


I have a python string which is basically a concatenation of 3 variables.I am using f-strings to make it a string. It looks like this now:

my_string = f'{getattr(RequestMethodVerbMapping, self.request_method).value} {self.serializer.Meta.model.__name__} {self.request_data['name']}'

which gives me the output:

Create IPGroup test-create-demo-098

Exactly the output that I want. However, as is obvious the line is too long and now Pylint starts complaining so I try to break up the line using multiline f-strings as follows:

my_string = f'''{getattr(RequestMethodVerbMapping, self.request_method).value} 
                {self.serializer.Meta.model.__name__} {self.request_data['name']}'''

Pylint is now happy but my string looks like this:

Create 
                  IPGroup test-create-demo-098

What is the best way of doing this so that I get my string in one line and also silence Pylint for the line being longer than 120 chars?


Solution

  • It is possible to concat f-strings with just whitespace in between, just like ordinary strings. Just parenthesize the whole thing.

    my_string = (f'{getattr(RequestMethodVerbMapping, self.request_method).value}' 
                 f' {self.serializer.Meta.model.__name__}
                 f' {self.request_data["name"]}')
    

    It will compile to exactly the same code as your one-line string.

    It is even possible to interleave f-strings and non-f-strings:

    >>> print(f"'foo'" '"{bar}"' f'{1 + 42}')
    'foo'"{bar}"43