Handling characters not saved in variables with F'strings in Python 3

Asked

Viewed 87 times

0

To manipulate unsaved characters in variables with F'strings I do this:

print(f'{"String":^20}')

I wonder if this is right, or would it be a scam for the fact that I have to define the string inside the keys with double quotes, because if I use single quotes an error happens.

  • 1

    Why do you want to do this? This is looking like a XY problem. Without understanding the purpose of you wanting to do this, it is difficult to assess whether it would be gambiarra or not.

  • Using single quotes or double quotes is something else entirely. If the string starts with single quotes, then it ends with single quotes and then the double quotes will be a character like any other. If the string starts with double quotes, then it ends with double quotes and then single quotes will be a character like any other.

  • I totally understand. I started researching about F'strings, but I’ve never seen anyone use a string with quotes directly on the keys, so I ask. I could use the . format, and I’ve seen several exercises that use the . format with Python for manipulating strings outside variables, only never seen with F'strings.

  • You have to change the quotation marks because this is how it was defined: https://www.python.org/dev/peps/pep-0498/#escape-sequences

  • Got it, thanks @hkotsubo. I asked the question just because I hadn’t seen it anywhere else. If you want to answer the question, I will accept it, so we can close it, because I already have my answer. If you have no problem I can remove the question, but I would like to attribute the answer to you as it helped me.

  • 1

    Well, as Victor has already said, without more context, it’s hard to answer whether or not... It is a language resource and can be used (but like every resource, it can be misused as well, and it all depends on the context)

Show 1 more comment

1 answer

0

To use f-Strings, you have to decide if right after the f will want to use single quotes or double quotes. If you decide to use single quotes in f, then to write the string will have to use double quotes, but if you decide to use double quotes with the f, then you will have to use simple quotes with the f. For example:

print(f'{"String":^20}')

or

print(f"{'String':^20}")

You can use both f how much F.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.