How to double each letter of a word in Python
Double each letter of a word in Python
In this Answer, we’ll learn how to use Python to take a word as input and output it with doubled letters.
Example
Input: red
Output: rreedd
Solution
To solve this problem, we’ll use the repetition and concatenation properties of strings.
String repetition
In Python, any string when multiplied with a numeric value results in a repetition of the original string.
For example, when a string hello is multiplied by a number 2, the result is hellohello.
string = "hello"print(string*2)
Explanation
- Line 1: We store the string
helloin the variablestring. - Line 2: We print the result of the multiplication of a string with an integer.
String concatenation
When a string is added with another string, it results in the concatenation of both the strings.
For example, when a string hello is added to the string world, it results in the output helloworld.
string1="hello"string2="world"print(string1+string2)
Explanation
- Line 1: We store the string
helloin the variablestring1. - Line 2: We store the string
worldin the variablestring2. - Line 2: We print the result of the addition of a string with another string.
We need to repeat individual characters in the given problem instead of the whole word. To solve this, we will use both string repetition and concatenation together.
Solution
Take the input string and store it in a variable. Loop through the string using a for loop, multiply every character by 2, and add the resulting character to an output variable holding an empty string initially. This will double every character and add all the resulting characters to form an expected output string.
input_string = input()output=""for i in input_string:output = output + i*2print(output)
Enter the input below
Explanation
- Line 1: We store the input string in the variable
input_string. - Line 2: We store an empty string
""in the variableoutput. - Line 3: We iterate through the string using a
forloop. - Line 4: We multiply each character stored in the variable
iwith2and add it to the variableoutput. Store the result in the variableoutput. - Line 5: We print the
outputvariable.