0

i am pretty new to python coming from Java, C, and Haskell environment, i was wondering if there exist something similar to the following but with strings and not numbers, so i have:

for i in range(5,11)
    print "Index : %d" %i

and the result will be: 5, 6, 7, 8, 9, 10 (each in a new line of course). So, i want to have the same for strings, like:

for c in range("a","e")
    print "Alphabet : %s" %c

I am just curious and I have tried many things with both strings and chars but i could not obtain the result I want. Thanks in advance.

2
  • Not clear what result you expect. What is the result you want? Commented Jun 14, 2015 at 0:47
  • 1
    I assume he asks if python will understand that he wants the ASCII symbols between the two parameters. Can't test it right now, Commented Jun 14, 2015 at 0:50

2 Answers 2

3

Strings are iterable in Python, so you can simply do:

for c in 'abcde':
    print 'Alphabet:', c

Alphabet: a
Alphabet: b
Alphabet: c
Alphabet: d
Alphabet: e

If you want an alternative with an explicit range, there's the (rather ugly):

for c in range(ord('a'), ord('e')+1):
     print 'Alphabet:', chr(c)

Alphabet: a
Alphabet: b
Alphabet: c
Alphabet: d
Alphabet: e

range does not take strings as arguments in Python, so you have to convert the characters to their ASCII equivalents and then back again.

Sign up to request clarification or add additional context in comments.

Comments

1

Python 2 If you want to print only a range of the Alphabet you can not use range() for strings. you can only use it for integers, but you can do this:

Alphabet = 'abcdefghijklmnopqrstuvwxyz'
x = Alphabet[5:11]
print "Alphabet : %s" % x

The output is:

Alphabet : fghijk

If you want each string in a new line:

for i in x:
    print i

Output:

f
g
h
i
j
k

In Python 3 you would print like this:print(i)

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.