Characters can be:
- Letters
[A-Za-z]
- Numbers
[0-9]
- Symbols
[@ $ # ~ ]
- Unicode Characters Site
- Spaces
[' ']
- Escape Character
[\n \r \t \' \\ \b \f \ooo \xhh]
- Each character has an index
Char# 1 2 3 4 5 6 7 8 9 10 11 Char W E B E R S T A T E + Index 0 1 2 3 4 5 6 7 8 9 10 - Index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 # Select characters out of a string school = 'WEBER STATE' print ('character 1 :' + school[0]) --> print ('character 4 :' + school[3]) --> print ('character 7 :' + school[-4]) -->
- begin at
start
and extending up to but not includingend
- school[0:3] -->
WEB
start
blank
- start at index 0
- school[:3] r-->
WEB
end
blank
- go until the end of the string
- school[8:] -->
ATE
# Select a substring print ('start = 0 end = 4: ' + school[0:4]) --> print ('start = 0 end = 5: ' + school[0:5]) -->print ('start = 2 end = 5: ' + school[2:5]) --> print ('start = -5 end = : ' + school[-5:-1]) -->print ('start = -5 end = : ' + school[-5:]) --> print ('start = end = : ' + school[:]) -->
- String have a length property
- +
concatenate (combine strings)
- *
create multiple copies of the string
# combine string a = 'apple' b = 'sauce' print (a + b) --> print (a + b + a) --> print (a * 3) --> print (3 * a) -->
Can't combine strings and numbers unless you use format
# This will produce a TypeError age = 75 person = 'Scott is ' + age print (person) #Using the format string method age = 75 person = 'Scott is {}' print (person.format(age)) #Using the format string method for multiple items age = 75 hours = 10 person = 'Scott is {} he sleeps {} hours a day' print (person.format(age, hours)) #Using the format string method for multiple items with index age = 75 hours = 10 dogs = 5 person = 'Scott sleeps {1} hours a day. He is {0} years old. He has {2} dogs' print (person.format(age, hours, dogs))
illegal characters in a string require an escape character
Use
\followed by the character
- Escape Character
[\n \r \t \' \\ \b \f \ooo \xhh]
# use of single quote in string txt = "Scott's Dog" # or txt = 'Scott\s Dog' #Using the format string method age = 75 person = 'Scott is {}' print (person.format(age)) #Using the format string method for multiple items age = 75 hours = 10 person = 'Scott is {} he sleeps {} hours a day' print (person.format(age, hours)) #Using the format string method for multiple items with index age = 75 hours = 10 dogs = 5 person = 'Scott sleeps {1} hours a day. He is {0} years old. He has {2} dogs' print (person.format(age, hours, dogs))
capitalize()
first character to uppercasetitle()
first character of each word to uppercasecasefold()
lowercaselen()
return the length of the stringcount()
number of times a value occurs in a string- additional string methods
# capitilize the first letter name = 'scott' print (name.capitalize()) name = 'sCoTt' print (name.capitalize())