Saturday, September 30, 2023
HomeSoftware EngineeringEasy methods to Double Characters in Python

Easy methods to Double Characters in Python


The problem

Given a string, it’s important to return a string during which every character (case-sensitive) is repeated as soon as.

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

double_char("Hi there World") ==> "HHeelllloo  WWoorrlldd"

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

The answer in Python code

This will simply be achieved by looping by means of every character and appending it to a listing, which we then be part of and return on the finish:

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

Nonetheless, we may simplify this right down to a single record comprehension:

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

Or go one step additional:

def double_char(s):
    return ''.be part of(c * 2 for c in s)

Take a look at instances to validate our resolution

check.assert_equals(double_char("String"),"SSttrriinngg")
check.assert_equals(double_char("Hi there World"),"HHeelllloo  WWoorrlldd")
check.assert_equals(double_char("1234!_ "),"11223344!!__  ")
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments