Nume
Nume

Reputation: 183

Print the length of strings as numbers

I am trying to define a function, which prints the exact length of the string (which may be any length - based on user input), as numbers. For example:

string = "hello"

length of the string is 5, so the python prints this line:

"1 2 3 4 5"

and if

string = "notnow"

length of string is 6, so the python prints this line:

"1 2 3 4 5 6"

Upvotes: 2

Views: 226

Answers (5)

Nabil Khoury
Nabil Khoury

Reputation: 22

For this kinda problems, I like to combine list comprehension and a join. Something like this:

def indexify(text): 
    return ' '.join([str(x + 1) for x in range(len(text))])

Upvotes: 0

Paul Rooney
Paul Rooney

Reputation: 21619

string1 = "hello"
string2 = "notnow"

def lenstr(s):
    return ' '.join(map(str, range(1, len(s) + 1)))

print(lenstr(string1))
print(lenstr(string2))
print(lenstr(''))

In the case where the string has length 0, it prints nothing.

Upvotes: 1

Stidgeon
Stidgeon

Reputation: 2723

I'd go with enumerate, which does a very quick counting by character (in this case), and can be used with list comprehension very tidily:

for i, char in enumerate(string):
    print i+1,

where string is any string you want (from user input, or whatever). The print i+1 prints the enumeration (plus one, since indexing starts at 0) and the comma keeps it all on the same line.

You can use this along with the standard:

string = raw_input('Enter some text: ')

or input if you're in python 3.X

Upvotes: 1

user3813674
user3813674

Reputation: 2683

How about this:

ret = ""
string = "hello"

for i in range(len(string)):
    ret+=str(i+1) + " "

print ret

len("hello") is 5 and len("notnow") is 6. I don't know why these numbers in your question is off by 1.

Upvotes: 0

CubeOfCheese
CubeOfCheese

Reputation: 53

You could print x, x-1, x-2 and so on as long as the integer is positive.

Upvotes: 0

Related Questions