Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using f String to insert characters or symbols @

I have two variables that store two numbers in total. I want to combine those numbers and separate them with a comma. I read that I can use {variablename:+} to insert a plus or spaces or a zero but the comma doesn't work.

x = 42
y = 73
print(f'the number is {x:}{y:,}')

here is my weird solution, im adding a + and then replacing the + with a comma. Is there a more direct way?

x = 42
y = 73
print(f'the number is {x:}{y:+}'.replace("+", ","))

Lets say I have names and domain names and I want to build a list of email addresses. So I want to fuse the two names with an @ symbol in the middel and a .com at the end.

Thats just one example I can think off the top of my head.

x = "John"
y = "gmail"
z = ".com"
print(f'the email is {x}{y:+}{z}'.replace(",", "@"))

results in:

print(f'the email is {x}{y:+}{z}'.replace(",", "@"))
ValueError: Sign not allowed in string format specifier
like image 709
Barry Avatar asked Dec 07 '25 11:12

Barry


1 Answers

You are over-complicating things.

Since only what's between { and } is going to be evaluated, you can simply do

print(f'the number is {x},{y}') for the first example, and

print(f'the email is {x}@{y}{z}') for the second.

like image 119
DeepSpace Avatar answered Dec 10 '25 02:12

DeepSpace