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?
Parent
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?
Post
+
is string concatenation and only be applied by strings. Non-string operands like numbers or class instances must be converted to strings using str()
. That's all there really is to it, except Python has some syntactic sugar that hides this in certain situations.
When I have a list u
of things (i.e. may or may not be strings) that I want to combine into a string s
, my go to is:
s = "".join(map(str, u))
This is somewhat advanced Python syntax but it's not that complex. map
applies str
to every element of u
, and join
glues them all together with an empty string as a delimiter (so that we're not adding anything extra). This is easy to remember, easy to type, and works with everything. You can modify it with various ways as well, such as passing list/sequence comprehensions instead of u
or a lambda instead of str
.
Syntactic sugars include:
-
print
takes any object, not just strings, and will automatically convert to string. It can also handle multiple arguments. Thereforeprint(8, " cans of spam")
will work, (althoughprint(8 + " cans of spam")
will not, because the concatenation must evaluate before print). - String formatting also auto-converts. Therefore
"{} cans of {}".format(8, "spam")
will work.f"{8} cans of {meat_name}"
is just syntactic sugar for this. The%
operator is the same, but it's an ancient Python syntax and I consider it superseded by f-strings. - When you put strings next to each other like
"hello" "world"
the+
is implicit. Because, well, what else could you possibly mean besides concatenation?
1 comment thread