Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform string to f-string

How do I transform a classic string to an f-string?

variable = 42 user_input = "The answer is {variable}" print(user_input) 

Output: The answer is {variable}

f_user_input = # Here the operation to go from a string to an f-string print(f_user_input) 

Desired output: The answer is 42

like image 762
François M. Avatar asked Jun 26 '17 10:06

François M.


People also ask

How do I change strings to f string?

Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os. linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.

How do you convert a string to an F string in Python?

F-String literals start with an f , followed by any type of strings (i.e. single quotation, double quotation, triple quotation), then you can include your Python expression inside the string, in between curly brackets. Let's string to use an f-String in your Python shell: name = "f-String" print(f"hello {name}!")

How do you make an F string?

What are f-Strings in Python? Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.

Is F string better than format?

As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!


1 Answers

An f-string is syntax, not an object type. You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.

I'm assuming you want to use user_input as a template, so just use the str.format() method on the user_input object:

variable = 42 user_input = "The answer is {variable}" formatted = user_input.format(variable=variable) 

If you wanted to provide a configurable templating service, create a namespace dictionary with all fields that can be interpolated, and use str.format() with the **kwargs call syntax to apply the namespace:

namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'} formatted = user_input.format(**namespace) 

The user can then use any of the keys in the namespace in {...} fields (or none, unused fields are ignored).

like image 97
Martijn Pieters Avatar answered Sep 20 '22 10:09

Martijn Pieters