小能豆

Apostrophe prints out to terminal when concatenating a string

java

fairly new to python coding. Currently using python 3.11.6

I’ve been given a task to ask for a user input for their name, age, street number and street address and to print out a single sentence containing all those details

I have configured a code for this task It seems to be working fine, but the only issue is that once it prints the output variable it prints it as:

('Hi Phil', ' you are 7 years old. You live at 89a', ' hollywood')

For some reason I do not know, apostrophes show up surrounding the name, after the inputted house number and surrounding the street name

I’m not sure if it has to do with added commas to separate the variables but I only added in the comma’s because it shows up as a syntax error without it

name =  str(input("What is your name: "))
age = int(input("What is your age: "))
house_number = str(input("what is your house number: "))
street_name = str(input("What is your street name: "))
output = ("Hi " +name, " you are " +str(age) +" years old. You live at " +house_number, ' ' +street_name )
print (output)

with this code I was expecting it to print out:

Hello (name), you are (age) years old. You live at (house number, street name)

but it prints out:

'Hi (name)', ' you are (age) years old. You live at (house no.)', ' (street name)'

just wondering how to remove the apostrophes in the printed output and why that’s happening


阅读 70

收藏
2023-11-23

共1个答案

小能豆

The issue you’re encountering is related to how you are creating the output variable. You are using parentheses to create a tuple instead of a single string. When you print a tuple, Python adds apostrophes to represent the tuple. To fix this, you should concatenate the strings directly without creating a tuple. Here’s the modified code:

name = str(input("What is your name: "))
age = int(input("What is your age: "))
house_number = str(input("What is your house number: "))
street_name = str(input("What is your street name: "))

# Concatenate the strings directly
output = "Hi " + name + ", you are " + str(age) + " years old. You live at " + house_number + " " + street_name

print(output)

This way, the output variable is a single string, and when you print it, you won’t see the apostrophes around the values. Additionally, I added commas and spaces where needed for better readability in the output string.

Now, when you run the code, it should print something like:

Hi Phil, you are 7 years old. You live at 89a hollywood

This way, you concatenate the strings directly without creating a tuple, and the printed output should match your expectations.

2023-11-23