Home > database >  I want to add underscore after every 4th character in Python
I want to add underscore after every 4th character in Python

Time:02-18

This is a string I want add underscore after every 4th element

a = "asdfqwerzxcv"
l = list(a)

the output should be like asd_qwe_zxc_

CodePudding user response:

I'm not shure whether you ask about PMaybe try something like this:

a = "asdfqwerzxcv"

def underscore(x):
    l = list(a)
    for i in range(3, len(x), 4):
        l[i] = '_'
    return "".join(l)

print(underscore(a))

Result:

asd_qwe_zxc_

CodePudding user response:

One way you could do it using comprehensions and a ternary operator:

a = "asdfqwerzxcv"
b = ''.join([a[i] if (i 1)%4!=0 else "_" for i in range(len(a))])
print(b)

Output:

asd_qwe_zxc_

CodePudding user response:

You dont need to change the string to a list - can do for loops over strings:

def add_underscores(word, n):
    last_underscore = 0
    new_word = ""
    for chr in word:
        if last_underscore == n:
            new_word  = ("_")
            last_underscore=0
        new_word  =(chr)
        last_underscore  =1
    return new_word
    
print( add_underscores("asdfqwerzxcv", 3))
  • Related