简体   繁体   中英

How do I append the user input (integer) with a string in python?

rep_number = int(input('X time(s)'))

ther_note.append(+ rep_number + "time(s).")

TypeError: unsupported operand type(s) for +: 'int' and 'str'

You cannot append a string and an integer as one element so I think the easiest way would be to cast the integer into a string with str(rep_number) . You can also use format() to generate the whole thing as a string with ("{0} times").format(rep_num) .

You can't in your example, but there are ways. If you're just getting the input to print out and won't be using it as an actual integer you can just append the formatted string using an f-string

ther_note = []
rep_number = int(input('X time(s)'))
ther_note.append(f"{rep_number} times(s)")

If you need to use the number later on, store the numbers and add the text later on when you need it.

ther_note = []
rep_number = int(input('X time(s)'))
ther_note.append(rep_number)

for x in ther_note:
    print(f"{x + 100} times(s)")

Other ways to add ints and strs :

num = 10
sentence = "My age is "
print(sentence + str(num))

Or

num = 10
sentence = "My age is {}".format(num)
print(sentence)

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