Skip to content

Commit 92025fd

Browse files
committed
Create using_string_concatenation_instead_of_formatting.rst.
1 parent c502865 commit 92025fd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Using string concatenation instead of formatting
2+
================================================
3+
4+
Summary
5+
-------
6+
7+
Although string concatentation is significantly faster than string formatting, the Python community finds formatting to be much more readable. Therefore, when performance is not an issue (or formatting is required) choose string formatting over string concatenation.
8+
9+
Description
10+
-----------
11+
12+
The Python community places a high premium on readable code. PEP 20 states that "Readability counts." Although string concatenation performs better than string formatting, unless performance is an absolute top priority, use string formatting because it is generally agreed to be more readable.
13+
14+
Examples
15+
----------
16+
17+
Using string concatenation
18+
..........................
19+
20+
The simple module below uses string concatenation to print out some text. String concatenation is generally not the preferred way to join strings in Python.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
name = "Fred"
27+
28+
print "Hello, my name is " + name + "."
29+
30+
Solutions
31+
---------
32+
33+
Use string formatting
34+
.....................
35+
36+
The modified module below prints out the same message, this time using string formatting, which is the preferred method in the Python community for joining strings.
37+
38+
.. code:: python
39+
40+
name = "Fred"
41+
42+
print "Hello, my name is %s.".format(name)
43+
44+
References
45+
----------
46+
- `Stack Overflow - String Concatenation vs. String Substitution <http://stackoverflow.com/questions/376461/string-concatenation-vs-string-substitution-in-python>`_

0 commit comments

Comments
 (0)