String Processing: Basics


In [5]:
str1 = "hello!"
print str1
str2 = 'this is in apostrophes'
print str2
print type(str2)

firstName = input("Enter your name:")
print firstName


#greet = "Hello Bob"
#print greet[0]


hello!
this is in apostrophes
<type 'str'>
Enter your name:"Rachel"
Rachel

Practice Problems

Usernames


In [6]:
##Usernames v 1.0
def usernames():
    first = raw_input('Enter your first name: ')
    last = raw_input ('Enter your last name: ')
    uname = first[0]+last[:8]
    x = len(uname)
    print "Your username is %s" %(uname)
    print "There are %d characters in your username \
    and that's good enough for me."%(x)
usernames()


Enter your first name: rachel
Enter your last name: rakov
Your username is rrakov
There are 6 characters in your username     and that's good enough for me.

Months


In [7]:
def month():
#  A program to print abbreviation of a month, given its number

    # months is used as a lookup table
    months = "JanFebMarAprMayJunJulAugSepOctNovDec"

    n = input("Enter a month number (1-12): ")

    # compute starting position of month n in months
    pos = (n-1) * 3
    
    # Grab the appropriate slice from months
    monthAbbrev = months[pos:pos+3]

    # print the result    
    print "The month abbreviation is", monthAbbrev + "."

month()


Enter a month number (1-12): 4
The month abbreviation is Apr.

In [9]:
def month2():
    
    # months is a list used as a lookup table
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
              "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]
    
    n = input("Enter a month number (1-12): ")

    print "The month abbreviation is", months[n-1] + "."

month2()


Enter a month number (1-12): 9
The month abbreviation is Sept.

List Examples


In [11]:
s = "Now is the winter of our discontent"
#x = list(s)

x = s.split()
print x

string = " ".join(x)
print string


['Now', 'is', 'the', 'winter', 'of', 'our', 'discontent']
Now is the winter of our discontent

More Months Practice!


In [ ]:
def DateManip():
    datestr = raw_input("Enter a date in the format mm/dd/yyyy:")
    date = datestr.split("/")
    month = int(date[0])
    day = date[1]
    year = date[2]
    months = ["January", "February", "March", "April", "May", "June",
              "July", "August", "September", "October", "November", "December"]    
    month_check = month-1
    monthstr = months[month_check]

    print "Your date is", monthstr, day+",", year
#DateManip()

In [ ]:


In [ ]: