3

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
Barry
  • 311
  • 3
  • 13

2 Answers2

5

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
4

When you put something into "{}" inside f-formatting, it's actually being evaluated. So, everything which shouldn't put it outside the "{}". Some Examples:

x = 42
y = 73
print(f'Numbers are: {x}, {y}') # will print: 'Numbers are: 42, 73'
print(f'Sum of numbers: {x+y}') # will print: 'Sum of numbers: 115'

You can even do something like:

def compose_email(user_name, domain):
      return f'{user_name}@{domain}'

user_name = 'user'
domain = 'gmail.com'
print(f'email is: {compose_email(user_name, domain)}')

>>email is: user@gmail.com

For more examples see: Nested f-strings

Aaron_ab
  • 3,450
  • 3
  • 28
  • 42