目录
字符串的使用:
- Python程序中,如果我们把单个或多个字符用单引号或者双引号包围起来,就可以表示一个字符串。字符串中的字符可以是特殊符号、英文字母、中文字符、日文的平假名或片假名、希腊字母、Emoji字符等。
- 以三个双引号或单引号开头的字符串可以折行
s1="hello.world"
s2='你好,' \
'世界'
print(s1,s2)
s3='''
hello,
world
xixi
'''
print(s3)
D:\装机软件\python\python.exe "D:/python code2020/test01/z字符串.py"
hello.world 你好,世界
hello,
world
xixi
Process finished with exit code 0
-
转义字符
- 可以在字符串中使用
\
(反斜杠)来表示转义,也就是说\
后面的字符不再是它原来的意义, - 例如:
\n
不是代表反斜杠和字符n
,而是表示换行;\t
也不是代表反斜杠和字符t
,而是表示制表符。 - 所以如果字符串本身又包含了
'
、"
、\
这些特殊的字符,必须要通过\
进行转义处理。例如要输出一个带单引号或反斜杠的字符串,需要用如下所示的方法。
s1 = '\'hello, world!\''
print(s1)
s2 = '\\hello, world!\\'
print(s2)
D:\装机软件\python\python.exe "D:/python code2020/test01/z字符串.py"
'hello, world!'
\hello, world!\
Process finished with exit code 0
Python中的字符串可以r
或R
开头,这种字符串被称为原始字符串,意思是字符串中的每个字符都是它本来的含义,没有所谓的转义字符。
# 字符串s1中\t是制表符,\n是换行符
s1 = '\time up \now'
print(s1)
# 字符串s2中没有转义字符,每个字符都是原始含义
s2 = r'\time up \now'
print(s2)
# 字符串s1中\t是制表符,\n是换行符
s1 = '\time up \now'
print(s1)
# 字符串s2中没有转义字符,每个字符都是原始含义
s2 = r'\time up \now'
print(s2)
- Python中还允许在
\
后面还可以跟一个八进制或者十六进制数来表示字符,例如\141
和\x61
都代表小写字母a
,前者是八进制的表示法,后者是十六进制的表示法。
另外一种表示字符的方式是在\u
后面跟Unicode字符编码,
s2 = '\u971c\u524d\u6708\u4e0b\u767d\u5c0f\u9c7c'
print(s2)
D:\装机软件\python\python.exe "D:/python code2020/test01/z字符串.py"
霜前月下白小鱼
Process finished with exit code 0
字符串的运算
- Python为字符串类型提供了非常丰富的运算符,
- 我们可以使用
+
运算符来实现字符串的拼接, - 可以使用
*
运算符来重复一个字符串的内容, - 可以使用
in
和not in
来判断一个字符串是否包含另外一个字符串, - 可以用
[]
和[:]
运算符从字符串取出某个字符或某些字符。 -
s1='hello,'+"world!" print(s1) s2="嘟嘟"*3 print(s2) print(s1+s2) s1*=4 print(s1) D:\装机软件\python\python.exe "D:/python code2020/test01/z字符串.py" hello,world! 嘟嘟嘟嘟嘟嘟 hello,world!嘟嘟嘟嘟嘟嘟 hello,world!hello,world!hello,world!hello,world! Process finished with exit code 0
在很多编程语言中,要表示一个有10个
a
的字符串,你只能写成"aaaaaaaaaa"
,但是在Python中,你可以写成'a' * 10
。
比较运算:
对于两个字符串类型的变量,可以直接使用比较运算符比较两个字符串的相等性或大小。需要说明的是,因为字符串在计算机内存中也是以二进制形式存在的,那么字符串的大小比较比的是每个字符对应的编码的大小
s1 = 'you are my sunshine .'
s2 = 'you are my star'
print(f's1 == s2,{s1==s2},;s1 < s2,{s1<s2};')
print(s2 == 'sunny')
print(s2 != 'sunny')
s3 = '白小鱼'
print(ord('白'), ord('小'),ord(a'鱼'))
s4 = '张萌萌'
print(ord('张'), ord('萌'), ord('萌'))
print(s3 > s4, s3 <= s4)
D:\装机软件\python\python.exe "D:/python code2020/test01/z字符串.py"
s1 == s2,False,;s1 < s2,False;
False
False
True
30333 23567 40060
24352 33804 33804
True False
Process finished with exit code 0
课程链接:https://github.com/jackfrued/Python-Core-50-Courses/blob/master
\u6b23\u4e8e\u6240\u9047\uff0c\u6682\u5f97\u4e8e\u5df1\uff0c\u5feb\u7136\u81ea\u8db3\uff0c\u4e0d\u77e5\u8001\u4e4b\u5c06\u81f3\u3002