# Filename: P05_Strings.py # Author: Joseph Chua # Date: 10/18/2016 # Purpose: Slicing a string into THREE pieces. # Other: http://repeatercreeper.me #======================================================================= # Logic - Assignment #1 #======================================================================= userInp = input("Enter Here: ") while (len(userInp) % 3) != 0: # Keep adding whitespace until divisible by 3 userInp += " " # Concatenation of whitespace def split(str, num): return [ str[i:i+num] for i in range(0, len(str), num) ] print ("Original String: " + userInp) # Creates 3 variables to store each slices. Sliced using 'split' function. slice1, slice2, slice3 = split(userInp, int(len(userInp) / 3)) # Prints the results in THREE slices. print("Slice #1: " + slice1) print("Slice #2: " + slice2) print("Slice #3: " + slice3) #======================================================================= # Logic - Assignment #2 #======================================================================= quote = input("Enter a quote: ") i = 0 if (len(quote.split(' '))) >= 2: splitQuote = quote.split(' ') while i != 3: if i == 0: print("Split: ", splitQuote) elif i == 1: ccString = "" for j in range(0, len(splitQuote)): ccString += splitQuote[j] print("Concatinate: ", ccString) else: charUse = "," print("Join: ", charUse.join(splitQuote)) i += 1 else: print("You entered an invalid quote!")
I'm mostly looking at my Assignment #2. It looks like it has plenty of room for improvements, but if you find something to improve on Assignment #1 to make it more concise that would be amazing.
So for Assignment #2 objective was as follows (copy & paste directly from the book):
Activity 2: Write the Python code to split, join, and concatenate a string.
- a) Allow the user to input a string (a famous quote) that will be manipulated within a While loop.
- a. Print the string that was entered.
- b) Within a WHILE loop that iterates three (3) times, manipulate the string.
- If the loop iteration is the first time, split the quote into separate words and print the result of the split operation.
- If the loop iteration is the second time, concatenate the split string (list of words) in an order you choose and print the result of the concatenation operation.
- If the loop iteration is the third time, join the split string content (list of words) with a character(s) of your choosing and print the result of the join operation.