Created
November 1, 2023 21:32
-
-
Save byinarie/2628e0f887e538c126f269cabf63c875 to your computer and use it in GitHub Desktop.
string interpolation example in python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
When you run this code it will generate the following output: | |
h%s%s%s%s%s%s%s%s%s%s | |
he%s%s%s%s%s%s%s%s%s | |
hel%s%s%s%s%s%s%s%s | |
hell%s%s%s%s%s%s%s | |
hello%s%s%s%s%s%s | |
hello %s%s%s%s%s | |
hello w%s%s%s%s | |
hello wo%s%s%s | |
hello wor%s%s | |
hello worl%s | |
hello world | |
''' | |
#/usr/bin/env python3 | |
# Initialize an empty string with %s placeholders | |
phrase = "%s" * 11 # There are 11 characters in "hello world" | |
# Characters to form "hello world" | |
characters = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] | |
# Initialize an empty string to store the result | |
result = "" | |
# Loop through each character and replace the placeholder | |
for char in characters: | |
# Replace the first occurrence of %s with the character | |
phrase = phrase.replace("%s", char, 1) | |
# Append the intermediate phrase to result | |
result += phrase + "\n" | |
# Store the modified phrase for the next iteration | |
phrase = phrase | |
# Print the final result | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment