Sample Code
s = "This is a sample string"
print(s)
print("It contains this many characters: ", len(s))
print("Here it is in upper case...")
print(s.upper())
print("Here it is split into a list:")
words = s.split()
for word in words:
print(word)
print("Here it is split by the letter \'a\'")
words = s.split("a")
for word in words:
print(word)
print("Here's the characters from index 1 to 3")
print(s[1:3])
print("Here's the sample string with the letter s changed to z")
print(s.replace("s","z"))
print("And now with the letter s changed to sausage...")
print(s.replace("s","sausage"))
print("And now with the spaces removed...")
print(s.replace(" ",""))
print("Notice the original string is unchanged... ")
print(s)
Exercise
- Output the length of the String “I never saw a purple cow”
- Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
- Use \n to create a string that prints out the words to Happy Birthday. Make it yourself (Happy Birthday dear Kevin). Print out the string
- Use the replace method to print out the words to Happy Birthday, this time for Mr Lightfoot
- Output the String “I never saw a purple cow” as a list of separate words.
- Output the initial letters of the String “I never saw a purple cow”
- Prompt the user to enter a String. Output a list of the initial letters of the words input. Example: input “British Broadcasting Corporation” output “B”,”B”,”C”.
Extension
- Prompt the user to enter a String. Output a String with the vowels replaced with *’s. Example: input “I never saw a purple cow” output “* n*v*r s*w * p*rpl* c*w”
- Prompt the user to enter a string. Output the string as separate words in alternate upper and lower case: SO it LOOKS like THIS example
- Output the following list as one String: words = [“Calling”, “occupants”, “of”, “interplanetary”, “craft”]
- Prompt the user to enter a string. Output the number of vowels in the String.
- A palindrome is a string that reads the same forwards and backwards. Examples are “radar” and “rotavator”. Write a program that accepts a String as input and outputs “Palindrome” if the String is a palindrome, and “Not Palindrome” otherwise.
Like this:
Like Loading...
Related
Published by Tony Ballantyne
Writer and Tech blogger
View all posts by Tony Ballantyne