Skip to content

Commit 49bee99

Browse files
authored
Merge pull request #379 from realpython/string-concatenation-python
Sample code for the string concatenation article
2 parents ca89195 + fc79f8a commit 49bee99

File tree

7 files changed

+67
-0
lines changed

7 files changed

+67
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Efficient String Concatenation in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [Efficient String Concatenation in Python](https://realpython.com/python-string-concatenation/).

string-concatenation-python/age.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def age_group(age):
2+
if 0 <= age <= 9:
3+
result = "a Child!"
4+
elif 9 < age <= 18:
5+
result = "an Adolescent!"
6+
elif 19 < age <= 65:
7+
result = "an Adult!"
8+
else:
9+
result = "in your Golden Years!"
10+
print("You are " + result)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def concatenate(iterable, sep=" "):
2+
sentence = iterable[0]
3+
for word in iterable[1:]:
4+
sentence += sep + word
5+
return sentence
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
2+
3+
with open("output.txt", "w") as f:
4+
print(*words, sep="\n", file=f)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from io import StringIO
2+
3+
words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
4+
5+
sentence = StringIO()
6+
sentence.write(words[0])
7+
for word in words[1:]:
8+
sentence.write(" " + word)
9+
10+
sentence.getvalue()
11+
result = sentence.getvalue()
12+
13+
print(result)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from io import StringIO
2+
3+
sentence = StringIO()
4+
while True:
5+
word = input("Enter a word (or './!/?' to end the sentence): ")
6+
if word in ".!?":
7+
sentence.write(word)
8+
break
9+
if sentence.tell() == 0:
10+
sentence.write(word)
11+
else:
12+
sentence.write(" " + word)
13+
14+
print("The concatenated sentence is:", sentence.getvalue())
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
data = [
2+
["Name", "Age", "Hometown"],
3+
["Alice", "25", "New York"],
4+
["Bob", "30", "Los Angeles"],
5+
["Charlie", "35", "Chicago"],
6+
]
7+
8+
9+
def display_table(data):
10+
max_len = max(len(header) for header in data[0])
11+
sep = "-" * max_len
12+
for row in data:
13+
print("|".join(header.ljust(max_len) for header in row))
14+
if row == data[0]:
15+
print("|".join(sep for _ in row))
16+
17+
18+
display_table(data)

0 commit comments

Comments
 (0)