首页 > 编程语言 > 详细

Python 学习笔记06【字符串操作】

时间:2019-10-05 11:54:46      阅读:73      评论:0      收藏:0      [点我收藏+]

6.1 处理字符串

6.1.1 字符串字面量

Python默认是单引号开始,单引号结束。

如何在字符串中使用单引号呢 ?如下,使用双引号 或者 转义字符

6.1.2 使用双引号

1 >>> spam = "this is Alice‘s cat"
2 >>> spam
3 "this is Alice‘s cat"

6.1.3 转义字符

1 >>> spam = this is Alice\‘s cat
2 >>> spam
3 "this is Alice‘s cat"

常用转义字符

转义字符        打印为
\‘        ‘
\"        "
\t        制表符
\n        换行符
\\        \

6.1.4 原始字符串

在字符串之前加上r

>>> spam = rthis is Alice\‘s cat
>>> spam
"this is Alice\\‘s cat"
>>> print(spam)
this is Alice\s cat
>>> 

6.1.5 用三重引号的多行字符串

多行字符串的起止是 三个 单引号 或 双引号。

三重引号之间的所有引号、换行符、回车符 都是字符串的一部分,其中的特殊字符不需要转义。

>>> spam = """
hello huahua,
this is huihui‘s toy, it costs 13$, so
don‘t touch it ,OK ?
"""
>>> spam
"\nhello huahua,\nthis is huihui‘s toy, it costs 13$, so\ndon‘t touch it ,OK ?\n" #实际存储形式
>>> print(spam) # 打印形式

hello huahua,
this is huihuis toy, it costs 13$, so
dont touch it ,OK ?

6.1.6 多行注释

# 单行注释

三重引号:多行注释

6.1.7 字符串下表和切片

字符串可以看做是由单个字符组成的列表,每个字符都是列表的表项。

6.1.8 字符串的in 和 not in 操作符

6.2 有用的字符串方法

6.2.1 upper(), lower(), isupper(), islower()

字符串至少含有一个字母,并且所有的字母都是大写或者小写,isupper() islower()才返回True

6.2.2 isX方法

  • isalpha() 返回True, 如果字符串只包含字母,并且非空
  • isalnum() 返回True,如果字符串只包含字母和数字,并且非空
  • isdecimal() 返回True,如果字符串只包含数字字符,并且非空
  • isspace() 返回True,如果字符串只包含 空格、制表符 和 换行符,且非空
  • istitle() 返回True, 如果字符串仅包含大写字符开头、后面都是小写字母的单词

6.2.3 字符串方法 startswith() 和 endswith()

6.2.4 字符串方法 join() 和 split()

join用法: 分隔符.join([列表项])
>>> .join([my,name,is,huahua]) my name is huahua


split用法:待分割字符串.split(分隔符)

>>> ‘my-name-is-huahua‘.split(‘-‘)
[‘my‘, ‘name‘, ‘is‘, ‘huahua‘]

6.2.5 用rjust(), ljust() 和 center()方法对齐文本

1 >>> huahua.rjust(20, #)
2 ##############huahua
3 >>> huahua.ljust(20,#)
4 huahua##############

6.2.6 strip() rstrip() lstrip()删除单侧/双侧空白字符

strip() 有可选字符串参数,用于删除两侧/单侧特定字符

>>> 555adfasdaf555.strip(555)
adfasdaf

 

Python 学习笔记06【字符串操作】

原文:https://www.cnblogs.com/wooluwalker/p/11624218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!