python第十章:数据类型之字符串
一,什么是字符串
用单引号’或双引号”括起来的文本
如果文本中包含有单引号或双引号时怎么办?
|
1
2
3
4
|
# 用单引号定义包含双引号的字符串print('he said:"ok"')# 用双引号定义包含单引号的字符串print("he said:'ok'") |
运行结果:
he said:"ok"
he said:'ok'
二,转义字符
转义字符\可以用来在双引号定义的字符串中显示双引号,
或单引号定义的字符串中显示单引号,
而且\n可以用来表示换行
|
1
2
3
4
5
6
|
# 转义字符可以处理同时包含单引号和双引号的字符串print("he said:\"i'm ok\"")# 用\n换行 \n表示换行print("python\nphp\nlinux")# 打印\时,也要加上转义字符进行转义print("c:\\windows\\program") |
代码运行结果:
he said:"i'm ok"
python
php
linux
c:\windows\program
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/13/python-di-shi-zhang-shu-ju-lei-xing-zhi-zi-fu-chuan/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,不用转义字符来表示换行?
两个”’可以用来包含多行文本
|
1
2
3
4
5
|
# 不用转义字符换行,用两个'''来包含多行文本print('''pythonphplinux''') |
代码运行结果:
python
php
linux
四,连接字符串
+可以连接两个字符串
|
1
2
3
4
5
6
|
# 字符串的连接:用+连接print("hello,"+"world")# 字符串的连接:用, 连接,注意打针时两个字符串中间会留有一个空格print("hello,", "world")# 字符串的连接:直接连接,两个字符串中间没有运算符print("hello,""world") |
代码运行结果:
hello,world
hello, world
hello,world

浙公网安备 33010602011771号