Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip white spaces in Python without using a string method?

I am fairly new to programming and have been learning some of the material through HackerRank. However, there is this one objective or challenge that I am currently stuck on. I've tried several things but still cannot figure out what exactly I am doing wrong.

Objective: Read N and output the numbers between 0 and N without any white spaces or using a string method.

N = int(input())
listofnum = []

for i in range(1, N +1):
    listofnum.append(i)
print (*(listofnum))

Output :

1 2 3
like image 851
CTLearn Avatar asked Sep 01 '26 23:09

CTLearn


1 Answers

N = int(input())
answer = ''
for i in range(1, N + 1):
    answer += str(i)
print(answer)

This is the closest I can think of to 'not using any string methods', although technically it is using str.__new__/__init__/__add__ in the background or some equivalent. I certainly think it fits the requirements of the question better than using ''.join.

like image 146
Alex Hall Avatar answered Sep 04 '26 12:09

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!