Boston Python Workshop 3/Data types: Difference between revisions

imported>Jesstess
imported>Jesstess
 
(3 intermediate revisions by the same user not shown)
Line 40:
==Strings==
 
* Strings are bits of text, and contain characters like numbers, letters, whitespace, and punctuation.
* String are surrounded by quotes.
* Use triple-quotes (""") to create whitespace-preserving multi-line strings.
Line 46 ⟶ 47:
>>> "Hello"
'Hello'
</pre>
 
====String concatenation====
 
<pre>
>>> "Hello" + "World"
HelloWorld
>>> "Hello" + "World" + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> "Hello" + "World" + str(1)
'HelloWorld1'
</pre>
 
====Printing strings====
 
<pre>
<b>Printing strings with '+'</b>:> print "Hello" + "World"<br />
HelloWorld
>>> print "Hello", "World"
Hello World
<b>Printing strings with ','</b>:> print "Hello", "World", 1<br />
Hello World 1
</pre>
 
Line 56 ⟶ 81:
was US $1.4 million.
</pre>
 
====Types====
 
<pre>
Line 61 ⟶ 88:
<type 'str'>
</pre>
 
<b>String concatenation with '+'</b>: "Hello" + "World"<br />
<b>Printing strings with '+'</b>: print "Hello" + "World"<br />
<b>Printing strings with ','</b>: print "Hello", "World", 1<br />
 
==Booleans==
Line 125 ⟶ 148:
 
* Use lists to store data where order matters.
* Lists are indexed starting with 0.
 
====List initialization====
Line 240 ⟶ 263:
>>> my_string
'Hello Jessica'
</pre>
 
* One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:
 
<pre>
>>> h = "Hello"
>>> h[0] = "J"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> h = "J" + h[1:]
>>> h
'Jello'
</pre>
 
Anonymous user