Python - String Manipulation Example



strings-example.py
___________________________________________________
#!/usr/bin/python
def main():
    s = 'this is a string'

    print(s.capitalize())
    print(s.title())
    print(s.upper())
    print(s.swapcase())
    print(s.find('is'))
    print(s.replace('this', 'that'))
    print(s.strip())
    print(s.isalnum())
    print(s.isalpha())
    print(s.isdigit())
    print(s.startswith("this"))
    pos = s.find('str', 1, 15)
    if pos == -1:
        print("did NOT find it")
    elif pos == 10:
        print ("found it at 10")
    else:
        print("found it")

    print("++++++++++++++++++++++++")

    str = "Hello World!"    print(str[2:])   # llo World!

    print(str[2:5])    # llo

    print(str[:7])     # Hello W

    print(str[:-2])    # Hello Worl

    print(str[-2:])    # d!

    print(str[2:-2])   # llo Worl

    print(str[::-1])   # this reverses the whole string

    print(str[::2])    # this skips characters going forward: HloWrd



if __name__ == "__main__": main()
___________________________________________________



Output:
___________________________________________________
This is a string
This Is A String
THIS IS A STRING
THIS IS A STRING
2
that is a string
this is a string
False
False
False
True
found it at 10
++++++++++++++++++++++++
llo World!
llo
Hello W
Hello Worl
d!
llo Worl
!dlroW olleH
HloWrd

___________________________________________________



almirsCorner.com

No comments:

Post a Comment