3

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
4
  • Okay, so in your own words, why does the code do the wrong thing? Can you think of a way to change the code to do the right thing? Why not? Where exactly are you confused? If it's not your code, do you understand the code? Commented Dec 31, 2020 at 18:12
  • i don't want spaces in string to be included . output i want is 'H#l#o W#r#d' .here space between hello world is maintained Commented Dec 31, 2020 at 18:16
  • 2
    Okay. Think about the logic of your code. Why does it do the wrong thing? In your own words, what should change in the program's logic, in order to make it do the right thing instead? So, write the code for that new logic. Commented Dec 31, 2020 at 18:16
  • What about list('Hello World') instead of the first loop? Commented Dec 31, 2020 at 18:26

8 Answers 8

8

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'
Sign up to request clarification or add additional context in comments.

Comments

5

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()

2 Comments

Did not know about isspace() +1
Changing the value of increment doesn't do anything.
1

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)

Comments

1

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# A T#s#'

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

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

This code gives the output: 'H#l#o W#r#d T#i# #s A T#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'

1 Comment

i think you can increment j when encountering ' ' ... so the code would work.
1

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)

Comments

0

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 += ' '

Comments

0

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

Comments

0

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() 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.