Strings and Console Output Flashcards
String
A data type; can contain letters, numbers, and symbols.
eg. Name = Ryan (Ryan is the string value)
age = 19
food - cheese
Escaping Characters
Characters that cause trouble in code because Python thinks they’re ending the code (the apostrophe is one) - fix this by putting a backslash before them eg. ‘There's)
Index
A number assigned to a character in a string. Always starts counting from “0”
String methods
Let you perform certain tasks for strings
Eg. len(), lower(), upper(), str()
len()
string method that gets the length (number of characters) of a string - the variable goes into the ()
lower()
String method that removes capitalization in a string - call like variable.lower()
upper()
String method that adds capitalization in a string - call like variable.upper()
str()
A string method that turns non-strings into strings eg. str(2)
Dot Notation
Eg. variable.upper()
The dot that separates them is dot notation and used for upper() and lower() string methods. Methods using dot notation only work with strings.
Used to print strings and variables to the console
String Concatenation
Combining strings together using arithmetic operators
Explicit String Conversion
Used to combine a string with a non-string - need to convert non-string to a string - uses str()
String formatting with %
”%” operator after a string can combine a string with variables
Replaces %s with the string variable that comes after it
Eg. print “Hello %s” % (name)
What is happening here?
name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?")
print “Ah, so your name is %s, your quest is %s, “ \
“and your favorite color is %s.” % (name, quest, color)
String formatting is being used to insert the variables name, quest, and colour into the print command using the %s and % operators. The program will accept the raw input to each question and put it into the print command.
datetime.now()
Retrieves the current date and time