How to say for every character in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anjum114
    New Member
    • Jan 2008
    • 2

    How to say for every character in a string

    Well I have program in which i have look into every character of a string.
    Is there a method in python

    str = " the world is small"

    for every char in str ( I don't know how to do this)
  • anjum114
    New Member
    • Jan 2008
    • 2

    #2
    Sorry got it. I am just new to python and still learning

    Solution:

    We just have to treat the string as array of characters so


    for i in range (0,len(str))
    print str[i]

    will do fine

    Comment

    • Smygis
      New Member
      • Jun 2007
      • 126

      #3
      Originally posted by anjum114
      Sorry got it. I am just new to python and still learning

      Solution:

      We just have to treat the string as array of characters so


      for i in range (0,len(str))
      print str[i]

      will do fine

      NOOOOOOOOOOO! Now zeh worlt wil endet! Or maybe not ;)

      You can iterate directly over the string instead.
      [code=python]
      worldString = " the world is small"
      for i in worldString:
      print i
      [/code]

      And dont use str as a variable name. You will overwrite the str() function.

      [code=python]
      >>> str(666)
      '666'
      >>> str = "Hello"
      >>> str(666)
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: 'str' object is not callable
      >>>
      [/code]

      It wont end the world but its a bad habit.

      Comment

      Working...