-3

so i want to write this simple java code in python, but i cant, i want to print all the Strings letters form the first index to the last, so if my string is "josh", i want to print:

j 
o 
s
h

or like this java code:

   String name = josh;
   for(int i = 0; i < josh.length(); i++){
   print(josh.CharAt(i));
 }

i cant find any method that is like charAt, i'm guessing that it doesn't exists but there has to some other way to do it, i know its kinda dumb question, but i couldn't find anything online or here(on this website) to help me, so any ideas?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Gigalala
  • 439
  • 1
  • 8
  • 24
  • 1
    Take a look at the concept of 'iterables' in Python. As per Preet's answer, you can treat a string as a list of characters. Alternatively, the equivalent to charAt() is the list offset: josh[0]=="j". – nOw2 Oct 13 '13 at 11:23

1 Answers1

4

Try this:

name = "josh"
for i in name:
    print i
    # print(i) # python 3

name is the variable to which we assign string literal "josh". name is a str (or unicode in Python 3)

we iterate over name since strings are iterable (have __iter__() methods) with the loop iteration syntax. Each consecutive character is assigned to loop variable i per iteration over name's length.

Note that we cannot assign to name[i], only read from it since strings are immutable in python.

Preet Kukreti
  • 8,417
  • 28
  • 36