Detailed explanation of the basic knowledge of string types in Python

高洛峰
Release: 2017-03-13 15:34:29
Original
1502 people have browsed it

This article mainly introduces the basic knowledge learning tutorial of string type in Python, including escape character and string splicing and original string For basic knowledge explanation, friends who need it can refer to

If there are many middle classification methods for natural language classification, such as English, French, Chinese, etc., this classification method is the most common. In linguistics, there are also ways to classify languages, such as language families and so on. I propose a classification method here. This classification method has not yet been widely recognized by the broad masses of the people and researchers. However, I believe that the saying "the truth is in the hands of a few people" can be used at least here to explain to myself. Be brave.

My way of dividing it: one is to splice two elements in the language (such as two words) together to produce a new element (such as a new word); the other is to splice two elements together Together, you just get a juxtaposition of these two elements. For example, "good" and "people", the two elements spliced ​​together are "good people", and the splicing of 3 and 5 (that is, the sum of integers) together is 8. If you think it is 35, then It belongs to the second category.

Abstract my division:

One is: △ + □ = ○
The other is: △ + □ = △ □
Ours In language, the above two categories are inseparable, either the first category or the second category.

What a genius. Please applaud.

String
When I was complacent, I Googled it and found out that I was not that smart. The Wikipedia entry for strings said this:

String (String) is a limited series of zero or more characters. Generally recorded as s=a[1]a[2]...a[n].
See how great Wikipedia is. It has given a situation I imagined a vivid name, called a string, which is essentially a string of characters.

According to this definition, "Hello, World", which made a programmer feel great twice before, is a string. In other words, regardless of whether it is written in English, Chinese or some other language, the written text can be treated as a string. Of course, the special symbols in it can also be treated as a string, such as spaces, etc.

Strictly speaking, a string in Python is an object type. This type is represented by str, usually wrapped in single quotes '' or double quotes "".

Strings, like the numbers mentioned before, are both object types, or values. Of course, the expression methods are still different.


"I love Python." 'I love Python.' 'I LOVE PYTHON.' 'I LOVE PYTHON.'
Copy after login


It can be seen from these two examples that the result is the same whether single quotes or double quotes are used.


>>> 250
250
>>> type(250)
<type &#39;int&#39;>

>>> "250"
&#39;250&#39;
>>> type("250")
<type &#39;str&#39;>
Copy after login


Look carefully at the difference above. It is also 250. One is not placed in quotation marks, and the other is placed in quotation marks. Use type()Function Let’s check and find that they are actually two different object types. The former is int type, and the latter is str type, which is string type. Therefore, please be aware that not all numbers are int (or float). You must see where it is. If it is inside quotation marks, it is a string. If you don't know what type it is, let type() help you figure it out.

Let’s practice strings.


>>> print "good good study, day day up"
good good study, day day up
>>> print "----good---study---day----up"
----good---study---day----up
Copy after login


After print, all strings are printed. Note that it is inside double quotes, and the quotes are not part of the string. It is telling the computer that it is wrapped in a string.

Thinking readers must have found something wrong with the above sentence. What should I do if I want to treat the following sentence as a string?

What's your name?
This question is very good, because there is a single quote in this sentence. If you type it directly in interactive mode like above, it will look like this:


>>> &#39;What&#39;s your name?&#39;
File "<stdin>", line 1
 &#39;What&#39;s your name?&#39;
  ^
SyntaxError: invalid syntax
Copy after login


The SyntaxError (syntax error) boot prompt appears. This is telling us that there is an error here, and the type of error is SyntaxError. , followed by the explanation of this error "invalid syntax" (invalid syntax). Pay special attention to the fact that there is a ^ symbol above the error message, followed by a single quotation mark. Needless to say, you can guess that it is probably telling us that there may be an error here.

在 python 中,这一点是非常友好的,如果语句存在错误,就会将错误输出来,供程序员改正参考。当然,错误来源有时候比较复杂,需要根据经验和知识进行修改。还有一种修改错误的好办法,就是讲错误提示放到 google 中搜索
上面那个值的错误原因是什么呢?仔细观察,发现那句话中事实上有三个单引号,本来一对单引号之间包裹的是一个字符串,现在出现了三个(一对半)单引号,computer 姑娘迷茫了,她不知道单引号包裹的到底是谁。于是报错。

解决方法一:双引号包裹单引号


>>> "What&#39;s your name?"
"What&#39;s your name?"
Copy after login


用双引号来包裹,双引号里面允许出现单引号。其实,反过来,单引号里面也可以包裹双引号。这个可以笼统地成为二者的嵌套。

解决方法二:使用转义符

所谓转义,就是让某个符号不在表示某个含义,而是表示另外一个含义。转义符的作用就是它能够转变符号的含义。在 Python 中,用 \ 作为转义符(其实很多语言,只要有转义符的,都是用这个符号)。


>>> &#39;What\&#39;s your name?&#39;
"What&#39;s your name?"
Copy after login


是不是看到转义符 \ 的作用了。

本来单引号表示包括字符串,它不是字符串一部分,但是如果前面有转义符,那么它就失去了原来的含义,转化为字符串的一部分,相当于一个特殊字符了。

变量和字符串
前面讲过变量无类型,对象有类型了,比如在数字中:


>>> a = 5
>>> a
5
Copy after login


其本质含义是变量 a 相当于一个标签,贴在了对象 5 上面。并且我们把这个语句叫做赋值语句。

同样,在对字符串类型的对象,也是这样,能够通过赋值语句,将对象与某个标签(变量)关联起来。


>>> b = "hello,world"
>>> b
&#39;hello,world&#39;
>>> print b
hello,world
Copy after login


还记得我们曾经用过一个 type 命令吗?现在它还有用,就是检验一个变量,到底跟什么类型联系着,是字符串还是数字?


>>> type(a)
<type &#39;int&#39;>
>>> type(b)
<type &#39;str&#39;>
Copy after login


有时候,你会听到一种说法:把a称之为数字型变量,把 b 叫做字符(串)型变量。这种说法,在某些语言中是成立的。某些语言,需要提前声明变量,然后变量就成为了一个筐,将值装到这个筐里面。但是,Python 不是这样的。要注意区别。

拼接字符串
还记得我在本节开篇提出的那个伟大发现吗?就是将两个东西拼接起来。

对数字,如果拼接,就是对两个数字求和。如:3+5,就计算出为 8。那么对字符串都能进行什么样的操作呢?试试吧:


>>> "Py" + "thon"
&#39;Python&#39;
Copy after login


跟我那个不为大多数人认可的发现是一样的,你还不认可吗?两个字符串相加,就相当于把两个字符串连接起来。(别的运算就别尝试了,没什么意义,肯定报错,不信就试试)

>>> "Py" - "thon"  # 这么做的人,是脑袋进水泥了吧?
Copy after login
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: &#39;str&#39; and &#39;str&#39;
Copy after login


用 + 号实现连接,的确比较简单,不过,有时候你会遇到这样的问题:

>>> a = 1989
>>> b = "free"
>>> print b+a
Copy after login
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate &#39;str&#39; and &#39;int&#39; objects
Copy after login


这里引入了一个指令:print,意思就是打印后面的字符串(或者指向字符串的变量),上面是 Python2 中的使用方式,在 Python3 中,它变成了一个函数。应该用 print(b+a)的样式了。
报错了,其错误原因已经打印出来了(一定要注意看打印出来的信息):cannot concatenate 'str' and 'int' objects。原来 a 对应的对象是一个 int 类型的,不能将它和 str 对象连接起来。怎么办?

原来,用 + 拼接起来的两个对象,必须是同一种类型的。如果两个都是数字,毫无疑问是正确的,就是求和;如果都是字符串,那么就得到一个新的字符串。

修改上面的错误,可以通过以下方法:


>>> print b + `a`  
free1989
Copy after login


注意,\ 是反引号,不是单引号,就是键盘中通常在数字1左边的那个,在英文半角状态下输入的符号。这种方法,在编程实践中比较少应用,特别是在 Python3 中,已经把这种方式弃绝了。我想原因就是这个符号太容易和单引号混淆了。在编程中,也不容易看出来,可读性太差。

常言道:“困难只有一个,解决困难的方法不止一种”,既然反引号可读性不好,在编程实践中就尽量不要使用。于是乎就有了下面的方法,这是被广泛采用的。不但简单,更主要是直白,一看就懂什么意思了。

>>> print b + str(a) 
free1989
Copy after login

用 str(a)实现将整数对象转换为字符串对象。虽然 str 是一种对象类型,但是它也能够实现对象类型的转换,这就起到了一个函数的作用。其实前面已经讲过的 int 也有类似的作用。比如:

>>> a = "250"
>>> type(a)
<type &#39;str&#39;>
>>> b = int(a)
>>> b
250
>>> type(b)
<type &#39;int&#39;>
Copy after login

提醒列位,如果你对 int 和 str 比较好奇,可以在交互模式中,使用 help(int),help(str)查阅相关的更多资料。

还有第三种:

>>> print b + repr(a) #repr(a)与上面的类似
free1989
Copy after login

这里 repr()是一个函数,其实就是反引号的替代品,它能够把结果字符串转化为合法的 python 表达式

可能看官看到这个,就要问它们三者之间的区别了。首先明确,repr()和 \ 是一致的,就不用区别了。接下来需要区别的就是 repr()和 str,一个最简单的区别,repr 是函数,str 是跟 int 一样,一种对象类型。

Python 转义字符
在字符串中,有时需要输入一些特殊的符号,但是,某些符号不能直接输出,就需要用转义符。所谓转义,就是不采用符号本来的含义,而采用另外一含义了。下面表格中列出常用的转义符:

转义字符
描述
\(在行尾时) 续行符
\反斜杠符号
\'单引号
\"双引号
\a响铃
\b退格(Backspace)
\e转义
\000
\n换行
\v纵向制表符
\t横向制表符
\r回车
\f换页
\oyy八进制数,yy 代表的字符,例如:\o12 代表换行
\xyy十六进制数,yy 代表的字符,例如:\x0a 代表换行
\other其它的字符以普通格式输出


以上所有转义符,都可以通过交互模式下 print 来测试一下,感受实际上是什么样子的。例如:


>>> print "hello.I am qiwsir.\     # 这里换行,下一行接续
... My website is &#39;http://qiwsir.github.io&#39;."
hello.I am qiwsir.My website is &#39;http://qiwsir.github.io&#39;.

>>> print "you can connect me by qq\\weibo\\gmail" #\\ 是为了要后面那个 \
you can connect me by qq\weibo\gmail
Copy after login


raw_input 和 print
分别在交互模式下,将这个两个函数操练一下。

>>> raw_input("input your name:")
input your name:python
&#39;python&#39;
Copy after login

输入名字之后,就返回了输入的内容。用一个变量可以获得这个返回值。

>>> name = raw_input("input your name:")
input your name:python
>>> name
&#39;python&#39;
>>> type(name)
<type &#39;str&#39;>
Copy after login

而且,返回的结果是 str 类型。如果输入的是数字呢?

>>> age = raw_input("How old are you?")
How old are you?10
>>> age
&#39;10&#39;
>>> type(age)
<type &#39;str&#39;>
Copy after login

返回的结果,仍然是 str 类型。

再试试 print(),看前面对它的说明,是比较复杂的。没关系,我们从简单的开始。在交互模式下操作:

>>> print("hello, world")
hello, world
>>> a = "python"
>>> b = "good"
>>> print a
python
>>> print a,b
python good
Copy after login

比较简单吧。当然,这是没有搞太复杂了。

特别要提醒的是,print()默认是以 \n 结尾的,所以,会看到每个输出语句之后,输出内容后面自动带上了 \n,于是就换行了。

有了以上两个准备,接下来就可以写一个能够“对话”的小程序了。

#!/usr/bin/env python
# coding=utf-8

name = raw_input("What is your name?")
age = raw_input("How old are you?")

print "Your name is:", name
print "You are " + age + " years old."

after_ten = int(age) + 10
print "You will be " + str(after_ten) + " years old after ten years."
Copy after login

对这段小程序中,有几点说明

前面演示了 print()的使用,除了打印一个字符串之外,还可以打印字符串拼接结果。

print "You are " + age + " years old."
Copy after login

注意,那个变量 age 必须是字符串,如最后的那个语句中:

print "You will be " + str(after_ten) + " years old after ten years."
Copy after login

这句话里面,有一个类型转化,将原本是整数型 after_ten 转化为了 str 类型。否则,就包括,不信,你可以试试。

同样注意,在 after_ten = int(age) + 10 中,因为通过 raw_input 得到的是 str 类型,当 age 和 10 求和的时候,需要先用 int()函数进行类型转化,才能和后面的整数 10 相加。

这个小程序,是有点综合的,基本上把已经学到的东西综合运用了一次。请看官调试一下,如果没有通过,仔细看报错信息,你能够从中获得修改方向的信息。

原始字符串
所谓原始字符串,就是指字符串里面的每个字符都是原始含义,比如反斜杠,不会被看做转义符。如果在一般字符串中,比如

>>> print "I like \npython"
I like 
python
Copy after login

这里的反斜杠就不是“反斜杠”的原始符号含义,而是和后面的 n 一起表示换行(转义了)。当然,这似乎没有什么太大影响,但有的时候,可能会出现问题,比如打印 DOS 路径(DOS,有没有搞错,现在还有人用吗?)

>>> dos = "c:\news"
>>> dos
&#39;c:\news&#39;  # 这里貌似没有什么问题
>>> print dos # 当用 print 来打印这个字符串的时候,就出问题了。
c:
ews
Copy after login

如何避免?用前面讲过的转义符可以解决:

>>> dos = "c:\\news"
>>> print dos
c:\news
Copy after login

此外,还有一种方法,如:

>>> dos = r"c:\news"
>>> print dos
c:\news
>>> print r"c:\news\python"
c:\news\python
Copy after login

状如 r"c:\news",由 r 开头引起的字符串,就是原始字符串,在里面放任何字符都表示该字符的原始含义。

这种方法在做网站设置网站目录结构的时候非常有用。使用了原始字符串,就不需要转义了。

The above is the detailed content of Detailed explanation of the basic knowledge of string types in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!