Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on How can I build a string from smaller pieces?
Post
How can I build a string from smaller pieces?
Suppose I have some variables like:
>>> count = 8
>>> status = 'off'
I want to combine them with some hard-coded text, to get a single string like
'I have 8 cans of Spam®; baked beans are off'
.
Simply writing the values in sequence only works for literal strings:
>>> 'one' 'two'
'onetwo'
>>> 'I have' count 'cans of Spam®; baked beans are' status
File "<stdin>", line 1
'I have' count 'cans of Spam®; baked beans are' status
^^^^^
SyntaxError: invalid syntax
(Python 3.9 and below will only highlight the "c" of count
; this improvement was added in 3.10)
Using commas to separate the values gives a tuple instead of a single string:
>>> 'I have', count, 'cans of Spam®; baked beans are', status
('I have', 8, '; baked beans are', 'off')
"Adding" the strings doesn't work either (I know this is not like mathematics, but it works in some other languages!):
>>> 'I have' + count + 'cans of Spam®; baked beans are' + status
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
How am I meant to do it?
1 comment thread