简体   繁体   中英

printing variable that contains string and 2 other variables

var_a = 8
var_b = 3

var_c = "hello my name is:",var_a,"and",var_b,"bye"
print(var_c)

When I run the program var_c gets printed out like this: ('hello my name is:', 8, 'and', 3, 'bye') but all the brackets etc get printed as well, why is this and is there a way to get rid of those symbols?

If I run the program like this:

print("hello my name is:",var_a,"and",var_b,"bye")

I don't have that problem

You can format your string to get your expected string output.

var_c = "hello my name is: {} and {}, bye".format(var_a, var_b)

As commented, your existing output is due to the variable being returned as a tuple, whereas you want it as one string.

在Python 3.6+中,您可以使用新的f-strings( 格式化的字符串文字 ):

var_c = f"hello my name is: {var_a} and {var_b}, bye"

var_c is actually a tuple, so print interprets it like that and you get its representation printed.

var_a = 8
var_b = 3
var_c = "hello my name is:", var_a, "and", var_b, "bye"

but you could just tell print to use the tuple as arguments with *

print(*var_c)

result:

hello my name is: 8 and 3 bye

(of course this is theorical, it's better to use str.format as other answers said)

您应该将var_c创建为字符串,如下所示

var_c = "hello my name is: %s and %s bye" % (var_a, var_b)
var_c = "hello my name is:",var_a,"and",var_b,"bye"

with this line, you are making var_c as tuple... to make it string make it like

var_d = "hello my name is:%s and %s bye" % (var_a,var_b)
print(var_d)

and it will output

hello my name is:8 and 3 bye

Your program is creating a tuple and you print the tuple:

var_a = 8
var_b = 3

var_c = "hello my name is:", var_a, "and", var_b, "bye"
print(var_c)

output:

('hello my name is:', 8, 'and', 3, 'bye') 

Alternatively print like this:

for item in var_c:
    print(item+' ', end='')

output:

hello my name is: 8 and 3 bye

That's because you are using syntax to create a tuple!

tup = "a", "b", "c", "d"

Refer this : https://www.tutorialspoint.com/python/python_tuples.htm .

If you just want to concatenate these you can write:

var_c = "hello my name is: " + str(var_a) + " and " + str(var_b) + " bye"
var_a = 8
var_b = 3

var_c = "hello my name is:", var_a, "and", var_b, "bye"
print(var_c)

output:

('hello my name is:', 8, 'and', 3, 'bye') 

Alternatively print like this:

for item in var_c:
    print(item+' ', end='')

output:

hello my name is: 8 and 3 bye

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM