温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python的字符串怎么表示

发布时间:2022-03-29 17:13:43 来源:亿速云 阅读:196 作者:iii 栏目:移动开发

这篇文章主要讲解了“Python的字符串怎么表示”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python的字符串怎么表示”吧!

字符串的表示方式

  • 单引号 " "

  • 双引号 " "

  • 多引号 """ """"  、 """ """

print("hello world") print("hello world") print("""hello world""") # 输出结果 hello world hello world hello world

为什么需要单引号,又需要双引号

因为可以在单引号中包含双引号,或者在双引号中包含单引号

# 单双引号 print("hello "poloyy" world") print("this is my name "poloyy"") # 输出结果 hello "poloyy" world this is my name "poloyy"

多行字符串

正常情况下,单引号和双引号的字符串是不支持直接在符号间换行输入的,如果有需要可以用多引号哦!

# 多行字符串 print(""" hello world """) print(""" this is my name poloyy """) # 输出结果 hello world this is my name poloyy

转义符

在字符前加  就行

常见的有

  • :换行

  • :缩进

  • :回车

栗子

比如在字符串双引号间还有一个双引号,就需要用转义符

# 转义符 print("hello "poloyy" world") print("my name is "poloyy"") # 输出结果 hello "poloyy" world my name is "poloyy"

假设  只想当普通字符处理呢?

print("反斜杠  是什么") print("换行符是什么  ") # 输出结果 反斜杠  是什么 换行符是什么

window 路径的栗子

print("c: othingtype") print("c: othingtype") # 输出结果 c: othing c: type c: othingtype

更简洁的解决方法

用转义符会导致可读性、维护性变差,Python 提供了一个更好的解决方法:在字符串前加r

print(r"c: othingtype") # 输出结果 c: othingtype

字符串运算:下标和切片

获取字符串中某个字符

字符串是一个序列,所以可以通过下标来获取某个字符

# 获取字符串某个字符 str = "hello world" print(str[0]) print(str[1]) print(str[6]) print(str[-1]) print(str[-5]) # 输出结果 h e w d l

如果是负数,那么是倒数,比如 -1 就是倒数第一个元素,-5 就是倒数第五个元素

获取字符串中一段字符

Python 中,可以直接通过切片的方式取一段字符

切片的语法格式

str[start : end : step]
  • start:闭区间,包含该下标的字符,第一个字符是 0

  • end:开区间,不包含该下标的字符

  • step:步长

栗子

print("hello world"[:] ", "hello world"[:])  # 取全部字符 print("hello world"[0:] ", "hello world"[0:])  # 取全部字符 print("hello world"[6:] ", "hello world"[6:])  # 取第 7 个字符到最后一个字符 print("hello world"[-5:] ", "hello world"[-5:])  # 取倒数第 5 个字符到最后一个字符 print("hello world"[0:5] ", "hello world"[0:5])  # 取第 1 个字符到第 5 个字符 print("hello world"[0:-5] ", "hello world"[0:-5])  # 取第 1 个字符直到倒数第 6 个字符 print("hello world"[6:10] ", "hello world"[6:10])  # 取第 7 个字符到第 10 个字符 print("hello world"[6:-1] ", "hello world"[6:-1])  # 取第 7 个字符到倒数第 2 个字符 print("hello world"[-5:-1] ", "hello world"[-5:-1])  # 取倒数第 5 个字符到倒数第 2 个字符 print("hello world"[::-1] ", "hello world"[::-1])  # 倒序取所有字符 print("hello world"[::2] ", "hello world"[::2])  # 步长=2,每两个字符取一次 print("hello world"[1:7:2] ", "hello world"[1:7:2])  # 步长=2,取第 2 个字符到第 7 个字符,每两个字符取一次 # 输出结果 hello world"[:] hello world hello world"[0:] hello world hello world"[6:] world hello world"[-5:] world hello world"[0:5] hello hello world"[0:-5] hello hello world"[6:10] worl hello world"[6:-1] worl hello world"[-5:-1] worl hello world"[::-1] dlrow olleh hello world"[::2] hlowrd hello world"[1:7:2] el

感谢各位的阅读,以上就是“Python的字符串怎么表示”的内容了,经过本文的学习后,相信大家对Python的字符串怎么表示这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI