7.2 String Methods

String Methods

There are various methods you can call on strings to change them or check if they contain certain characters.
You can view a full list of them here
These are the string methods that you should know:
  • upper - converts all alphabetic characters to uppercase
  • lower - converts all alphabetic characters to lowercase
  • split - returns an array of the string split by a certain pattern (by default, the string is split by spaces)
  • isalpha - returns True if all characters in the string are alphabetic
  • isdigit - returns True if all characters in the string are digits
  • strip - strips all whitespace from the beginning and end of the character
# string methods message = "hey dude" print(message) # prints "hey dude" message = message.upper() print(message) # prints "HEY DUDE" message = "THIS WAS IN ALL CAPS" print(message) # prints "THIS WAS IN ALL CAPS" message = message.lower() print(message) # prints "this was in all caps" message = "one two three four five" # prints ['one', 'two', 'three', 'four', 'five'] print(message.split()) message = "tahiti, it's, a, magical, place" # prints ['tahiti', " it's", ' a', ' magical', ' place'] print(message.split(",")) message = "hello" print(message.isalpha()) # True message = "12345" print(message.isalpha()) # False message = "12345" print(message.isdigit()) # True message = "hello world" print(message.isdigit()) # False message = " lots of white space " print(message) message = message.strip() print(message + "|")
View code on GitHub.
Output of the above code:
hey dude HEY DUDE THIS WAS IN ALL CAPS this was in all caps ['one', 'two', 'three', 'four', 'five'] ['tahiti', " it's", "a", 'magical', 'place'] True False True False lots of white space lots of white space|
Remember, these are also methods, so just like with list methods, you have to do variable_name.method(). Just doing method() by itself will either not work or cause an error.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.