***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Basic String Operations

    Python provides several ways to access the individual characters in a string. Strings also have methods that allow you to perform operations on them.

    Iterating over a String with the for Loop

    One of the easiest ways to access the individual characters in a string is to use the for loop.

    Here is the general format:

    for variable in string:

    statement

    statement

    etc.

    Example:

    name = 'Juliet'

    for ch in name:

    print(ch)

    The name variable references a string with six characters, so this loop will iterate six times.

    Indexing

    Another way that you can access the individual characters in a string is with an index. Each character in a string has an index that specifies its position in the string. Indexing starts at 0, so the index of the first character is 0, the index of the second character is 1, and so forth.

    Example:

    my_string = 'Roses are red'

    print(my_string[0], my_string[6], my_string[10])

    This code will print the following:

    R a r

    The Python interpreter adds negative indexes to the length of the string to determine the character position. The index −1 identifies the last character in a string, −2 identifies the next to last character, and so forth.

    The following code shows an example:

    my_string = 'Roses are red'

    print(my_string[-1], my_string[-2], my_string[-13])

    This code will print the following:

    d e R

    IndexError Exceptions

    An IndexError exception will occur if you try to use an index that is out of range for a particular string.

    The len Function

    The len function can be used to get the length of a string.

    The following code demonstrates:

    city = 'Boston'

    size = len(city)

    The function returns the value 6, which is the length of the string 'Boston'. This value is assigned to the size variable.

    String Concatenation

    A common operation that performed on strings is concatenation, or appending one string to the end of another string.

    The + operator produces a string that is the combination of the two strings used as its operands. The following interactive session demonstrates:

     >>> message = 'Hello ' + 'world'

     >>> print(message)

     Hello world

    >>>