Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Example- For Given string ‘Hello World’ returned string is ‘H#l#o W#r#d’.

i tried this code but spaces are also included in this . i want spaces to be maintain in between words

def changer():
    ch=[]
    for i in 'Hello World':
        ch.append(i)
    for j in range(1,len(ch),2):
        ch[j]= '#'
    s=''
    for k in ch:
        s=s+k
    print(s)
changer()

Output - H#l#o#W#r#d


Output i want =  H#l#o W#r#d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
563 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can str.split on whitespace to get substrings, then for each substring replace all the odd characters with '#' while preserving the even characters. Then str.join the replaced substrings back together.

>>> ' '.join(''.join('#' if v%2 else j for v,j in enumerate(i)) for i in s.split())
'H#l#o W#r#d'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...