2

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"
6
  • 2
    Have you tried anything already? Also, your length of the string calculation is off by one. Commented Jan 18, 2016 at 3:43
  • 1
    Yeah, there are 5 letters in "hello" Commented Jan 18, 2016 at 3:47
  • Reading material: functions len, range, str; use " ".join for additional credit :)
    – 9000
    Commented Jan 18, 2016 at 3:49
  • I can't figure out what to do with it. So far I have: a = str(input("Please enter a phrase: ")) length_of_a = len(a)
    – Nume
    Commented Jan 18, 2016 at 3:50
  • It's part of a LONG assignment - I have done the bit where I have to take a string and remove a character at random and then move that character to the END of the string. I just can't figure out how to make python print the length of the strings (starting from 1 and not 0) till the last character + 1.
    – Nume
    Commented Jan 18, 2016 at 3:52

5 Answers 5

1

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

1
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.

0

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.

1
  • Thank you. I ended up doing something similar.
    – Nume
    Commented Jan 18, 2016 at 4:36
0

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

0

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.