Manipulating Strings

Strings like "abc" are not officially of type list, but...

    
a string is, in essence, a list of characters.

You can loop through a string like you do a list. Take for instance this code to count how many 'a' characters are in a string:

i=0
count=0
while i<len(astring):
    # do something with each character
    if astring[i]=='a':
        count=count+1
             i=i+1

You can not modify a string by using an index:

    astring[i]==33

 in this sense, strings are immutable.

You can get a slice of a string. For instance, the following code gets the first two characters of a string:

    astring=astring[0:2]

To write a function to, say, replace the ith character of a string, you'd have to use string slices:

    def replace(astring,i,replacement):
        return astring[0:i]+replacement+astring[i+1:len(astring)]

You can build a string similar to how you build a list:

 def buildAsteriskString(count):
        newString = ""
        i=0
        while i<count:
            newString = newString+"*"
            i=i+1
  def buildAsteriskList(count):
        newList=[]
        i=0
        while i<count:
            newList.append("*")
            i=i+1
Note that there is actually a short-hand way of doing this:

asterisk  = '*' * count 

gives a string of asterisks count long.

Recent site activity