Basic knowledge of the string type in Python tutorial, python string
For natural language classification, there are many separation methods, such as English, French, and Chinese, which are the most common. In linguistics, there are also Classification Methods for languages, such as what languages. I propose a method, which has not yet been widely recognized by the masses and researchers. However, I believe that "truth is in the hands of a few people ", at least here, it can be used to make yourself brave.
My division: one is that two elements (such as two words) in a language are concatenated to produce a new element (such as a new word ); the other is that the two elements are spliced together to obtain the parallel display of the two elements. For example, "good" and "man", the two elements are spliced together as "good person", and 3 and 5 (that is, the integer sum) are combined as 8. If you think it is 35, that is the second type.
Abstract my method:
One is: △+ □= ○
Another type is: △+ □= △□
In our language, we can't do without the above two types, either the first type or the second type.
It's a genius. Applaud.
String
When I was so self-satisfied, I googled a bit and found that I was not so clever. Here is what I said when I read the string entry in Wikipedia:
String is a finite serial consisting of zero or multiple characters. It is generally recorded as s = a [1] a [2]... a [n].
Seeing the greatness of Wikipedia, it has taken an image name, called a string, which is essentially a string of characters.
According to this definition, the previous two "Hello, World" that made a programmer feel great is a string. In other words, the written text can be treated as strings regardless of English, Chinese, or other types of text. Of course, the special characters in the text can also be used as strings, such as spaces.
Strictly speaking, a string in Python is an object type, which is represented by str. It is usually enclosed by single quotation marks ('') or double quotation marks.
The string, like the number mentioned above, is an object type or a value. Of course, there are differences in representation.
"I love Python." 'I love Python.' 'I LOVE PYTHON.' 'I LOVE PYTHON.'
From the two examples, we can see that the results are the same whether single quotes or double quotes are used.
>>> 250250>>> type(250)<type 'int'>>>> "250"'250'>>> type("250")<type 'str'>
Take a closer look at the difference above, which is also 250. One is not placed in the quotation marks, the other is placed in the quotation marks, and the type () function is used to check the difference, it is found that they are two different object types, the former is int type, and the latter is str type, that is, string type. Therefore, please note that not all numbers are int (or float). You must check where it is. If it is in the quotation marks, it is a string. If you don't know what type it is, let type () Help.
Drill down the string.
>>> print "good good study, day day up"good good study, day day up>>> print "----good---study---day----up"----good---study---day----up
After print, all printed strings are printed. Note that it is in double quotation marks, which are not part of a string. It is telling the computer that it contains a string.
Those who love thinking will surely find that the above sentence has a problem. What should I do if I want to regard the following sentence as a string?
What's your name?
This problem is very good, because there is a single quotation mark in this sentence. If you enter it directly in the interactive mode as above, it will be like this:
>>> 'What's your name?'File "<stdin>", line 1 'What's your name?' ^SyntaxError: invalid syntax
The SyntaxError (syntax error) Pilot prompt is displayed. This indicates that an error exists here. The error type is SyntaxError, the following is an explanation of this error "invalid syntax" (invalid syntax ). Note that there is a ^ symbol on the top of the error prompt, with only one single quotation mark directly. You can also guess that it is probably telling us that there may be an error here.
In python, this is very friendly. If a statement has an error, it will output the error for the programmer to correct the reference. Of course, the error source is sometimes complicated and needs to be modified based on experience and knowledge. There is also a good way to modify the error, that is, to put the error prompt to google for search.
What is the cause of the above error? After careful observation, I found that there are actually three single quotes in the sentence. Originally, a pair of single quotes wrapped in a string. Now there are three (one-half) single quotes, and the computer girl is confused, she does not know who the single quotes are. An error is reported.
Solution 1: Enclose single quotes in double quotes
>>> "What's your name?""What's your name?"
Enclose in double quotation marks. single quotation marks are allowed in double quotation marks. In fact, double quotation marks can also be enclosed in single quotes. This can be a general nesting of the two.
Solution 2: Use escape characters
The so-called escape means that a symbol does not represent a meaning, but another meaning. An escape character is used to change the meaning of a symbol. In Python, use \ as the Escape Character (in fact, many languages use this symbol as long as there is an escape character ).
>>> 'What\'s your name?'"What's your name?"
See the role of the Escape Character.
A single quotation mark represents a string. It is not a part of a string, but if there is an escape character before it, it loses its original meaning and is converted to a part of the string, which is equivalent to a special character.
Variables and strings
As mentioned above, variables have no type and objects have a type, for example, in numbers:
>>> a = 5>>> a5
The essential meaning is that variable a is equivalent to a tag and pasted on Object 5. In addition, we call this statement a value assignment statement.
Similarly, for string-type objects, You can associate an object with a tag (variable) by using a value assignment statement.
>>> b = "hello,world">>> b'hello,world'>>> print bhello,world
Remember that we used a type command? Now it is still used to test a variable. What type is it related to? Is it a string or a number?
>>> type(a)<type 'int'>>>> type(b)<type 'str'>
Sometimes, you may hear a saying that a is a numeric variable and B is a string variable. This is true in some languages. In some languages, variables need to be declared in advance, and then the variables become a basket, and the values are loaded into this basket. However, Python is not like this. Note the differences.
Concatenated string
Do you still remember the great discovery I made at the beginning of this section? Is to splice two things.
If a number is spliced, the two numbers are summed. For example, 3 + 5 is calculated as 8. What operations can be performed on strings? Try it:
>>> "Py" + "thon"'Python'
This is the same as my findings that are not recognized by most people. Do you still not agree? Adding two strings is equivalent to connecting the two strings. (Don't try other operations. It makes no sense. You must report an error. If you don't believe it, try it)
>>> "Py"-"thon" # The person who does this is the cement of his head?
Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for -: 'str' and 'str'
Using the "+" sign to connect is indeed simple. However, you may encounter the following problems:
>>> a = 1989>>> b = "free">>> print b+a
Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects
Here we introduce a command: print, which means to print the subsequent string (or the variable pointing to the string). The above is the usage method in Python2. In Python3, it becomes a function. Print (B + a) should be used.
When an error is reported, the cause of the error has been printed out (you must check the printed information): cannot concatenate 'str' and 'int' objects. The original object corresponding to a is of the int type and cannot be connected to the str object. What should I do?
It turns out that the two objects combined with the plus sign (+) must be of the same type. If both are numbers, it is undoubtedly correct, that is, Sum. If both are strings, a new string is obtained.
To modify the preceding error, follow these steps:
>>> print b + `a` free1989
Note: \ is the inverse quotation mark, not a single quotation mark, or the symbol that is usually on the left of number 1 on the keyboard and entered in the half-width English. This method is rarely used in programming practices, especially in Python3, which has been abandoned. I think the reason is that this symbol is too easy to confuse with single quotes. In programming, it is not easy to see, and the readability is too bad.
As the saying goes: "There is only one difficulty and there are more than one way to solve it." Since the anti-quotation marks are not readable, do not use them in programming practice. As a result, the following method is widely used. It is not only simple, but also straightforward. You can understand what it means at a glance.
>>> print b + str(a) free1989
Use str (a) to convert an integer object to a string object. Although str is an object type, it can also implement object type conversion, which plays a role in a function. In fact, the int mentioned earlier has a similar effect. For example:
>>> a = "250">>> type(a)<type 'str'>>>> b = int(a)>>> b250>>> type(b)<type 'int'>
Reminder column. If you are curious about int and str, you can use help (int) and help (str) in interactive mode to view more information.
There are also three types:
>>> Print B + repr (a) # repr (a) is similar to free1989
Here, repr () is a function, which is actually a substitute for reverse quotation marks. It can convert the result string into a valid python expression.
If you may see this, you need to ask the difference between them. First, it is clear that the repr () and \ are consistent, so there is no difference. The next difference is repr () and str. The simplest difference is that repr is a function, and str is an object type like int.
Python escape characters
In a string, you sometimes need to enter some special symbols. However, if some symbols cannot be output directly, you need to use escape characters. The so-called escape means not to use the original meaning of the symbol, but to use another meaning. The following table lists common escape characters:
| Escape characters |
Description |
| \ |
(At the end of a row) |
| \ |
Backslash |
| \' |
Single quotes |
| \" |
Double quotation marks |
| \ |
Ring tones |
| \ B |
Backspace) |
| \ E |
Escape |
| \ 000 |
Null |
| \ N |
Line feed |
| \ V |
Vertical Tab |
| \ T |
Horizontal Tab |
| \ R |
Enter |
| \ F |
Form feed |
| \ Oyy |
Octal, which is a string of yy characters. For example, \ o12 indicates a line break. |
| \ Xyy |
Hexadecimal number. yy indicates the character. For example, \ x0a indicates a line break. |
| \ Other |
Other characters are output in normal format |
All the above escape characters can be tested using print in interactive mode to see what it actually looks like. For example:
>>> Print "hello. I am qiwsir. \ # line feed here, next line connection... my website is 'HTTP: // qiwsir. github. io '. "hello. I am qiwsir. my website is 'HTTP: // qiwsir. github. io '. >>> print "you can connect me by qq \ weibo \ gmail" #\\ is to ask the \ you can connect me by qq \ weibo \ gmail
Raw_input and print
Practice the two functions in interactive mode.
>>> raw_input("input your name:")input your name:python'python'
After the name is entered, the input content is returned. You can use a variable to obtain the returned value.
>>> name = raw_input("input your name:")input your name:python>>> name'python'>>> type(name)<type 'str'>
The returned result is of the str type. What if I enter a number?
>>> age = raw_input("How old are you?")How old are you?10>>> age'10'>>> type(age)<type 'str'>
The returned result is still 'str' type.
Try print () again. It is complicated to see the previous descriptions. It's okay. Let's start with a simple one. In interactive mode:
>>> print("hello, world")hello, world>>> a = "python">>> b = "good">>> print apython>>> print a,bpython good
It is relatively simple. Of course, this is not too complicated.
Note that print () ends with \ n by default. Therefore, \ n is automatically followed by the output content after each output statement.
With the above two preparations, you can write a small program capable of "conversation.
#!/usr/bin/env python# coding=utf-8name = raw_input("What is your name?")age = raw_input("How old are you?")print "Your name is:", nameprint "You are " + age + " years old."after_ten = int(age) + 10print "You will be " + str(after_ten) + " years old after ten years."
There are several notes for this small program
We have demonstrated the use of print (). In addition to printing a string, you can also print the String concatenation result.
print "You are " + age + " years old."
Note that the variable age must be a string, as in the last statement:
print "You will be " + str(after_ten) + " years old after ten years."
In this sentence, there is a type conversion, which converts the originally integer after_ten to the str type. Otherwise, you can try it.
Similarly, in after_ten = int (age) + 10, because the str type is obtained through raw_input, int () must be used to sum age and 10 () function type conversion to add to the integer 10.
This small program is a bit comprehensive, basically using what you have learned. Please check the official debugging. If the debugging fails, read the error information carefully and you will be able to obtain the information on the change direction.
Original string
The so-called original string means that each character in the string is the original meaning, such as a backslash, and will not be considered as an escape character. If it is in a general string, such
>>> print "I like \npython"I like python
Here, the backslash is not the original Symbolic Meaning of the "backslash", but a line break (escape) with n ). Of course, this does not seem to have much impact, but sometimes problems may occur, such as printing the DOS path (DOS, are there any mistakes? Are there other people using it now ?)
>>> Dos = "c: \ news" >>> dos 'C: \ news '# It seems that there is no problem> print dos # a problem occurs when print is used to print the string. C: ews
How to avoid it? We can solve the problem by using the escape characters described above:
>>> dos = "c:\\news">>> print dosc:\news
In addition, there is another method, such:
>>> dos = r"c:\news">>> print dosc:\news>>> print r"c:\news\python"c:\news\python
Such as r "c: \ news". The string that starts with r is the original string. Any character in it indicates the original meaning of the character.
This method is useful when setting the website directory structure. If the original string is used, you do not need to escape it.
Articles you may be interested in:
- Conversion of Python strings, tuples, lists, and dictionaries
- Simple notes on Python string features and common string Methods
- Implementation of Python string objects
- Sharing Key Points of Python strings
- Example of string operation method developed in python
- Basic knowledge about strings and lists in Python Programming
- Translate strings in the Django framework in Python
- Conversion of Python strings to floating point functions
- How to convert a python string to a moles code
- Introduction to using the split () method to split strings in Python