简体   繁体   中英

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

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'

you can control the increment, by default 2 but, in case of spaces 1 to jump it and continue evaluating the next word

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

Since you said you don't want spaces to be included in the output, don't include them:

ch=[]
for i in 'Hello World':
    ch.append(i)
for j in range(1,len(ch),2):
    if ch[j] != " ": # don't 'include' spaces
        ch[j]= '#'
s=''
for k in ch:
    s=s+k
print(s)

There are a lot of very inconsistent answers here. I think we need a little more info to get you the solution you are expecting. Can you give a string with more words in it to confirm your desired output. You said you want every successive character to be a #, and gave an example of H#l#o W#r#d. Do you want the space to be included in determining what the next character should be? Or should the space be written, but skipped over as a determining factor for the next character? The other option would be 'H#l#o #o#l#' where the space is included in the new text, but is ignored when determining the next character.

Some of the answers give something like this:

string = "Hello World This Is A Test"

'H#l#o W#r#d T#i# I# AT#s#'

'H#l#o W#r#d T#i# #s AT#s#'

'H#l#o W#r#d T#i# I# AT#s# '

This code gives the output: 'H#l#o W#r#d T#i# #s AT#s#'

string = 'Hello World This Is A Test'
solution = ''
c = 0

for letter in string:
    if letter == ' ':
        solution += ' '
        c += 1
    elif c % 2:
        solution += "#"
        c += 1
    else:
        solution += letter
        c += 1

If you actually want the desired outcome if including the whitespace, but not having them be a factor in determing the next character, alls you need to do is remove the counter first check so the spaces do not affect the succession. The solution would be: 'H#l#o #o#l# T#i# I# A #e#t'

You could use accumulate from itertools to build the resulting string progressively

from itertools import accumulate

s = "Hello World"

p = "".join(accumulate(s,lambda r,c:c if {r[-1],c}&set(" #") else "#"))

print(p)

Using your algorithm, you can process each word individually, this way you don't run into issues with spaces. Here's an adaptation of your algorithm where each word is concatenated to a string after being processed:

my_string = 'Hello World'
my_processed_string = ''
for word in my_string.split(' '):
    ch = []
    for i in word:
        ch.append(i)
    for j in range(1, len(ch), 2):
        ch[j] = '#'
    for k in ch:
        my_processed_string += k
    my_processed_string += ' '

You can maintain a count separate of whitespace and check its lowest bit, replacing the character with hash depending on even or odd.

def changer():
    ch=[]
    count = 0 # hash even vals (skips 0 because count advanced before compare)
    for c in 'Hello World':
        if c.isspace():
            count = 0 # restart count
        else:
            count += 1
            if not count & 1:
                c = '#'
        ch.append(c)
    s = ''.join(ch)
    print(s)

changer()

Result

H#l#o W#r#d

I have not made much changes to your code. so i think this maybe easy for you to understand.

enter code here

def changer():
    ch=[]
    h='Hello World' #I have put your string in a variable
    for i in h:
        ch.append(i)

    for j in range(1,len(ch),2):
        if h[j]!=' ':  
           ch[j]= '#'
    s=''

    for k in ch:
        s=s+k
    print(s)
changer() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM