String
It is easy to create string objects in Python. The creation of a new string is done as long as the text you want is placed in a pair of quotes (see Listing 1). If you think about it, you may feel a little confused. After all, there are two types of quotes you can use: Single quotes (') and double quotes ("). Fortunately, Python once again solves this problem. You can use any kind of quotation mark to represent a string in Python, as long as the quotation marks are consistent. If the string starts with single quotes, it must end with single quotes and vice versa. If you do not follow this rule, a SyntaxError exception appears.
Listing 1. Create a string in Python
>>> sr= "Discover Python"
>>> type (SR)
<type ' str ' >
>>> sr= ' Discover Python '
>>> type (SR)
<type ' str ' >
>>> sr= ' Discover python:it ' s wonderful!
>>> sr= ' Discover python '
File ' <stdin> ', line 1
sr= ' Discover python '
^
syntaxerror : EOL while scanning single-quoted string
>>> sr= "Discover Python: \
... It ' s wonderful!
>>> print SR
Discover Python:it ' s wonderful!
As you can see from Listing 1, there are two other important aspects in addition to the string being enclosed in proper quotes. First, when you create a string, you can mix single and double quotes, as long as the string uses the same type of quotation marks at both the start and end positions. This flexibility allows Python to easily retain regular text data, which may require the use of single quotes to represent shorthand verb forms or affiliation, and to use double quotes to denote quoted text.
Second, if the string is too long in one line, you can use the Python continuous character: a backslash (\) to wrap the string. From an internal mechanism, the newline character is ignored when the string is created, as can be seen when the string is printed. You can use these two features together to create a string that contains a longer paragraph, as shown in Listing 2.
Listing 2. Creating Long strings
>>> passage = ' When using the Python programming language, one must proceed \
... with caution. This is because Python are so easy to use and can are so very much
fun. Failure to follow this warning the May leads to shouts of.
"Woohoo" or "Yowza".
>>> Print Passage when
using the Python programming language, one must proceed with caution.
This is because the Python is-so-easy to-use, and can-so-much fun.
Failure to follow this warning the May leads to shouts of "Woohoo" or "Yowza".
Editor's note: the example above has been folded to make the page layout more reasonable. In fact, it would have been shown as a long row.
Note that when you print the passage string, all formatting is deleted, leaving only a very long string. Typically, you can use a control character to represent a simple format in a string. For example, to represent a new row start, you can use a newline control character (\ n), and to indicate that you want to insert a tab character (the preset number of spaces), you can use the tab control character (\ t), as shown in Listing 3.
Listing 3. Using a control character in a string
>>> passage= ' \twhen using the Python programming language, one must proceed\n\ ... \twith caution. This is because the Python is-so-easy to-use, and\n\ ... \tcan are so much fun. Failure to follow this warning may lead\n\ ... \tto shouts of "Woohoo" or "Yowza". ' >>> print passage when US ing the Python programming language, one must proceed with caution. This is because the Python is-so-easy to-use, and can-so-much fun.
Failure to follow this warning the May leads to shouts of "Woohoo" or "Yowza". >>> passage=r ' \twhen using the Python programming language, one must proceed\n\ ... \twith caution. This is because the Python is-so-easy to-use, and\n\ ... \tcan are so much fun. Failure to follow this warning may lead\n\ ... \tto shouts of "Woohoo" or "Yowza". ' >>> print passage \twhen-usin G The Python programming language, one must proceed\n\ \twith caution. This is because the Python is-so-easy to-use, and\n\ \tcan are so much fun. Failure to follow this warNing May lead\n\ \tto shouts of "Woohoo" or "Yowza".
The first paragraph in Listing 3 uses the control character the way you intended. The paragraph has a good format and is very convenient to read. The second example, although also formatted, refers to what is called the original string, which is a string with no control characters applied. You can always recognize the original string because the starting quote for the string has an R character in front of it, which is the raw abbreviation.
I don't know what you're talking about, and while this approach works, creating a paragraph string seems very difficult. Of course there must be a better way. As always, Python provides a very simple way to create long strings that preserve the format used to create strings. This method uses three double quotes (or three single quotes) to start and end long strings. In this string, you can use any number of single and double quotes (see listing 4).
Listing 4. Use a three-quote string
>>> passage = "" "
... When using the Python programming language, one must proceed
... With caution. This is because Python are so easy to use, and
... Can is so much fun. Failure to follow this warning could lead
... To shouts of "Woohoo" or "Yowza".
... ""
>>> Print passage when
using the Python programming language, one must proceed with
caution. This is because the Python is-so-easy to-use, and can-so-much
fun. Failure to follow this warning the May leads to
shouts of "Woohoo" or "Yowza".
To use a string as an object
If you read any of the articles in the first two articles of this series, you will immediately emerge in your mind the phrase: in Python, everything is an object. So far, I haven't touched on the object attributes of strings in Python, but, as always, strings in Python are objects. In fact, a string object is an instance of the Str class. As you can see in part 2nd of exploring Python, the Python interpreter includes a built-in Help tool (shown in Listing 5) that provides information about the Str class.
Listing 5. Get Help on strings
>>> Help (str) help on
class str in module __builtin__:
class str (basestring)
| Str (object)-> str ing
|
| Return a nice string representation of the object.
| If The argument is a string, the return value is the same object.
|
| Method Resolution Order:
| STR
| Basestring
| Object
|
| Methods defined here:
|
| | __add__ (...)
| x.__add__ (y) <==> x+y
|
...
Strings created using single quotes, double quotes, and triple quotes syntax are still string objects. However, you can also use the Str class constructor to explicitly create a string object, as shown in Listing 6. The constructor can accept simple built-in numeric types or character data as parameters. Both methods can change what you enter into a new string object.
Listing 6. Creating a String
>>> Str ("Discover python")
' Discover python '
>>> str (12345)
' 12345 '
>>> STR (123.45)
' 123.45 '
>>> ' Wow, "+" that "+" is awesome. "
' Wow, that was awesome. '
>>> "Wow," "that" "is Awesome"
' Wow, that is Awesome '
>>> "wow!" *5
' wow! wow! wow! wow! wow! '
>>> sr = str ("Hello")
>>> ID (SR)
5560608
>>> sr = "World"
> >> SR
' Hello World '
>>> ID (SR)
3708752
The example in Listing 6 also shows several other important aspects of the Python string. First, by adding other strings together, you can create new strings, either by using the + operator or by simply connecting the strings with the appropriate quotes. Second, if you need to repeat a short string to create a long string, you can use the * operator to repeat the string for a certain number of times. As I said at the beginning of this article, in Python, strings are immutable sequences of characters, and the last few lines in the example above illustrate this, I first create a string and then modify it by adding another string. As you can see from the output of the two call to the ID method, the new string object that you create holds the result of adding text to the original string.
The Str class contains a number of useful methods for manipulating strings. You can use the Help interpreter to get information about this. Now let's take a look at four useful functions and demonstrate the tools of other Str class methods. Listing 7 shows the upper, lower, split, and join methods.
Listing 7. String method
>>> sr = "Discover python!"
>>> sr.upper ()
' DISCOVER python! '
>>> sr.lower ()
' Discover python! '
>>> sr = "This is a test!"
>>> sr.split ()
[' This ', ' is ', ' a ', ' test! ']
>>> sr = ' 0:1:2:3:4:5:6:7:8:9 '
>>> sr.split (': ')
[' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 '], ' 9 ']
>>> sr= ":"
>>> tp = (' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ')
>>> Sr.join (TP)
' 0:1:2:3:4:5:6:7:8:9 '
The first two methods upper and lower are easy to understand. They only convert the strings to uppercase or lowercase letters, respectively. The split method is useful because it splits a string into several smaller string sequences by using the token character (or any character in a given sequence of characters) as an indicator of the disconnect position. So the first Split method example uses the default token to split the string "This is a test", which can be any white-space character (this sequence includes spaces, tabs, and line breaks). The second split method demonstrates how to divide a string into a series of strings using a different token character (a colon in this case). The last example shows how to use the Join method, which, contrary to the split method, allows multiple short string sequences to form a long string. In this example, a colon is used to concatenate a sequence of strings consisting of a single character tuple.
Use a string as a container for characters
At the beginning of this article, I highlighted that strings in Python are immutable sequences of characters. The 2nd part of this series explores Python, and part 2nd describes tuple, which is also a constant sequence. Tuple supports accessing elements in a sequence by using index symbols, using fragments to detach elements from a sequence, and creating new tuples with specific fragments or by adding different fragments together. Depending on this situation, you might want to know if you can apply the same technique to a Python string. As shown in Listing 8, the answer is clearly "yes".
Listing 8. String method
>>> sr= "0123456789"
>>> sr[0]
' 0 '
>>> sr[1] + sr[0]
'
>> > Sr[4:8] # give me elements four through seven, inclusive
' 4567 '
>>> sr[:-1] # give me all El Ements but the last one
' 012345678 '
>>> sr[1:12] # Slice More than you can chew, no problem
' 123456789 '
>>> sr[:-20] # Go before the start?
'
>>> sr[12:] # go past
'
>>> Sr[0] + sr[1:5] + Sr[5:9] + sr[9]
' 0123456789 '
>>> sr[10]
traceback (most recent CAL L):
File "<stdin>", line 1, in?
Indexerror:string index out of range
>>> Len (SR) # Sequences have common methods, like to my length
10
In Python, it is easy to handle a string as a sequence of characters. You can get a single element, add different elements together, cut out several elements, and even add different pieces together. A very useful feature of slicing is that doing more slices before or after the beginning does not throw an exception, only starting or ending the sequence by default. Conversely, if you try to access a single element using an index other than the allowable range, you get an exception. This behavior illustrates why the Len method is so important.
Strings: Powerful Tools
In this article, I introduced the Python string, which is a constant sequence of characters. In Python, you can easily create strings using multiple methods, including using single quotes, double quotes, or more flexibly, even with a set of three quotes. Assuming that everything in Python is an object, you can use the underlying STR class method to get additional functionality or to use the string's sequential functionality directly.