Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

how replace every successive character in string with ‘#’ with python?

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

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

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...