Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

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?

+4
−1

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?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Somewhat meta comment on questions created to be self-answered (6 comments)
Post
+2
−0

+ 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. Therefore print(8, " cans of spam") will work, (although print(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?
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

2 comment threads

print() vs string creation (2 comments)
f-strings can take strings (1 comment)
print() vs string creation
Karl Knechtel‭ wrote over 1 year ago

In the (artificial) question here I intended specifically to distinguish the case of creating a new string (that could then be used within the program for other purposes). It's true that many people who need this kind of information are just trying to display something on screen; but I intended to post a separate Q&A for that task, referencing this one.

Karl Knechtel‭ wrote over 1 year ago

Quick update: the new Q&A is now live.