How to Double Characters in Python

0 min read 121 words

The challenge

Given a string, you have to return a string in which each character (case-sensitive) is repeated once.

double_char("String") ==> "SSttrriinngg"

double_char("Hello World") ==> "HHeelllloo  WWoorrlldd"

double_char("1234!_ ") ==> "11223344!!__  "

The solution in Python code

This can easily be done by looping through each character and appending it to a list, which we then join and return at the end:

def double_char(s):
    out = []
    for i in s:
        out.append(i+""+i)
    return "".join(out)

However, we could simplify this down to a single list comprehension:

def double_char(s):
    return "".join([i+''+i for i in s])

Or go one step further:

def double_char(s):
    return ''.join(c * 2 for c in s)

Test cases to validate our solution

test.assert_equals(double_char("String"),"SSttrriinngg")
test.assert_equals(double_char("Hello World"),"HHeelllloo  WWoorrlldd")
test.assert_equals(double_char("1234!_ "),"11223344!!__  ")
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags