Reputation: 307
I need something like this
accepted_string: An apple a day keeps the doctor away
resultant_string: Aapedyepteotrwy
And for this I have written this code:
accepted_string = input("enter")
add = ''
for count in range(0, len(accepted_string), 2):
if accepted_string[count] == " ":
count += 1
add = add + accepted_string[count]
else:
add = add + accepted_string[count]
print(add)
But this is giving me different output while passing the above sample input. The logic is also correct, then where is the error? I have to skip to next character whenever I encounter a whitespace. Please help me as I am new to this
Upvotes: 1
Views: 62
Reputation: 5344
you can remove space before hands instead of doing in for loop and make it list to convert in into array
Code:
accepted_string = input("enter")
add = ''
accepted_string = list(accepted_string.replace(" ", ""))
print(accepted_string)
for count in range(0, len(accepted_string), 2):
add = add + accepted_string[count]
print(add)
output:
['A', 'n', 'a', 'p', 'p', 'l', 'e', 'a', 'd', 'a', 'y', 'k', 'e', 'e', 'p', 's', 't', 'h', 'e', 'd', 'o', 'c', 't', 'o', 'r', 'a', 'w', 'a', 'y']
Aapedyepteotrwy
2nd code:
accepted_string = input("enter")
add = ''
char_count = 1
for count in range(0, len(accepted_string)):
if accepted_string[count] != " ":
char_count += 1
if char_count % 2 == 0:
add = add + accepted_string[count]
# add = add + accepted_string[count]
# else:
# add = add + accepted_string[count]
print(add)
output:
Aapedyepteotrwy
Upvotes: 0
Reputation: 73480
Simple string slicing with prior replacement:
>>> s = "An apple a day keeps the doctor away"
>>> s.replace(" ", "")[::2]
'Aapedyepteotrwy'
Upvotes: 2