If you like what you're reading here, you can find it at Wrox or purchase the entire book at Amazon. What is a String? A string is one of several data types that exist within the Python language. A data type, as the name implies, is a category that a particular type of data fits into. Every type of data you enter into a computer is segregated into one of these data types, whether they be numbers or letters, as is the case in this scenario. Giving data a type allows the computer to determine how to handle the data. For instance, if you want the program to show the mathematical equation 1+1 on a screen, you have to tell it that it is text. Otherwise, the program will interpret the data as a mathematical equation and evaluate it accordingly. You’ll get more into the different data types and how important it is to define them in a later chapter. For now however, know that a string is a data type that consists of any character, be it a letter, number, symbol, or punctuation mark. Therefore, the following are all examples of strings: “ Hello, how are you? ” “ 1+1 ” “ I ate 4 bananas ” “ !@#$%^ & *() ” Why the Quotes? When you type a string into Python, you do so by preceding it with quotes. Whether these quotes are single ( ' ), double( '' ), or triple( " " " ) depends on what you are trying to accomplish. For the most part, you will use single quotes, because it requires less effort (you do not need to hold down the Shift key to create them). Note, however, that they are interchangeable with the double and even triple quotes. Try typing in some strings. After you type in each sentence, press the Enter key to allow Python to evaluate your statement. Try It Out Entering Strings with Different Quotes Enter the following strings, keeping in mind the type of quotes (single or double) and the ends of lines (use the Enter key when you see that the end of a line has been reached):
‘This a string using a double quote’ > > > ‘This is a string with a single quote’ ‘This is a string with a single quote’ > > > “””This string has three quotes look at what it can do!””” ‘This string has three quotes\nlook at what it can do!’ > > >
blog comments powered by Disqus |
|
|
|
|
|
|
|