Introduction to Computer Programming-Python Strings
http://www.codeskulptor.org/#user41_tVBN1WGxih_0.py
http://www.codeskulptor.org/#user41_tVBN1WGxih_3.py
http://www.codeskulptor.org/#user41_tVBN1WGxih_6.py
http://www.codeskulptor.org/#user41_tVBN1WGxih_7.py
http://www.codeskulptor.org/#user19_8Pjk3FA32L_0.py
http://www.codeskulptor.org/#user41_2i9OuJoexj_2.py
http://www.codeskulptor.org/#user41_2i9OuJoexj_3.py
Strings are a fundamental data type that allow programs to store text.
Given the following python code, predict the output:
Code | Output-Completed by Student |
myName = "Joe" print type(myName) | <type 'str'> |
Each character of a string is indexed, where the first character is designated a position 0.
H | e | l | l | o | B | o | b | ||
Index |
Example of string indexing: print myName[2] Output: ___
String Constants
Code | Output |
print "" |
|
print 'Hello, world.' | Hello, world. |
print "Goodbye, cruel world." | Goodbye, cruel world. |
print "It's a beautiful day." | It's a beautiful day. |
print """This is | This is |
Why would we have the option of “ or ‘ to create a string?
" is useful when you have ' into the string and vice versa
Operations on Strings
We can concatenate (combine) strings. Here are some common METHODS** on strings. The method is indicated by the following format:
string.method(Arguments)
-this is a big deal-
Name* | Code | Output |
Concatenation | print 'hello' + ' ' + 'world!' | hello world! |
Copy | print 'hello' * 2 | hellohello |
Slice | print 'abcde'[1:3] | bc |
Find (letter) | print 'abcbac'.index('c') | 2 |
Find (string) | print 'abcbac'.index('ba') | 3 |
Count | print 'abcbac'.count('c') | 2 |
*You can access the API for details on all available string methods.
**Note: Some Python books/courses will call methods, functions, more on this later...