004-Python字符串
Python 字符串(str)
字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。创建字符串很简单,只要为变量分配一个值即可。
var1 = "Hello World!"
var2 = 'DaoKe ChuZi'
字符串的操作
1.查看字符串有那些方法
>>> a = "abc"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
2.通过[]截取字符串的方式取值
>>> a = "Hello Word!"
>>> a[:8]
'Hello Wo'
>>> a[:-2]
'Hello Wor'
3.字符串的更新,就如同对一个字符串重新赋值
>>> a
'Hello Word!'
>>> a = "HAHAHA"
>>> a
'HAHAHA'
转义字符
在需要在字符中使用特殊字符时,python用反斜杠()转义字符
转义字符 | 描述
---|---|---|---|---|---
\(在行尾时)| 续行符
\\ | 反斜杠符号
\' | 显示单引号
" | 显示双引号
\n | 换行
\r | 回车
Python字符串运算符
下表实例变量a值为字符串 "Hello",b变量值为 "Python":
操作符 | 描述 |实例
---|---|---|---|---|---
-
| 字符串连接 |a + b 输出结果: **HelloPython**
-
| 重复输出字符串 |a\*2 输出结果: **HelloHello**
[] | 通过索引获取字符串中字符 | a[1] 输出结果 e
[ : ] | 截取字符串中的一部分 | a[1:4] 输出结果 ell
in | 成员运算符 - 如果字符串中包含给定的字符返回 True |"H" in a True
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True |"W" not in a True
Python字符串格式化
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
>>> print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
我叫 小明 今年 10 岁!
符号 | 描述
---|---|---|---|---|---
%s | 格式化字符串
%d | 格式化整数
%f | 格式化浮点数字,可指定小数点后的精度
Python字符串内置函数:
1.将字符串的第一个字符转换为大写capitalize():
>>> a = "hello word!"
>>> a.capitalize()
'Hello word!'
2.返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格center()
>>> a = "www.umout.com"
>>> a
'www.umout.com'
>>> a.center(40,"*")
'*************www.umout.com**************'
3.用于统计字符串里某个字符出现的次数count(str, beg= 0,end=len(string))
统计"o" 在字符串a 中出现的次数
>>> a
'www.umout.com'
>>> a.count("o")
2
4.判断字符串是否依指定后缀结尾,是返回True否则返回False:endswith()
>>> a
'www.umout.com'
>>> a.endswith("m")
True
>>> a.endswith("o")
False
5.默认把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是8,expandtabs()
[root@linux-node1#>> /tmp]#cat a.py
# !/bin/bash/env python3
# _*_coding:utf-8_*_
str = "this is\tstring example....wow!!!"
print("原始字符串: " + str)
print ("替换 \\t 符号: " + str.expandtabs())
print ("使用16个空格替换 \\t 符号: " + str.expandtabs(16))
输出内容:
原始字符串8个空格: this is string example....wow!!!
替换 \t 符号为空格: this is string example....wow!!!
使用16个空格替换 \t 符号: this is string example....wow!!!
6.检测字符串中是否包含子指定的字符串,(可以指定检测的起始点)如果包含子返回开始的索引值,否则返回-1;默认从左往右,rfind()从右往左;find()
>>> a
'www.umout.com'
>>> a.find("umout")
4
>>> a.find("umout",3,10)
4
>>> a.find("xxx")
-1
>>> a.rfind("o")
11
>>> a.rfind("o",-7,-2)
6
7.检测字符串是否由字母和数字组成,是返回True否则返回False isalnum()
>>> hostname = "LinuxName"
>>> hostname.isalnum()
True
>>> hostname2 = "LinuxName123--"
>>> hostname2.isalnum()
False
8.检测字符串是否只有字母组成,是返回True否则返回False isalpha()
>>> name = "Jack"
>>> name.isalpha()
True
>>> name2 = "Jack li"
>>> name2.isalpha()
False
9.检测字符串是否只有(阿拉伯)数字组成,是返回True否则返回False isdigit()
>>> age = "12"
>>> age.isdigit()
True
>>> age2 = "12y"
>>> age2.isdigit()
False
10.检测字符串是否只有小写组成(区分大小写的)字符都算是小写,是返回True否则返回False islower()
>>> name = "bao lin8888--==$$%%##¥¥"
>>> name.islower()
True
>>> name2 = "bao linAA"
>>> name2.islower()
False
11.检测字符串是否只由(Unicode)数字组成,是返回True否则返回False isnumeric()
>>> age = "四44肆④"
>>> age.isnumeric()
True
>>> age = "33oneIX"
>>> age.isnumeric()
False
12.检测字符串是否只由空格组成(或\t \n \r),是返回True否则返回False isspace()
>>> name = " \t \n \r "
>>> name.isspace()
True
>>> name = " \t xxx \n "
>>> name.isspace()
False
13.检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写;是返回True否则返回False istitle()
>>> name = "My Name Is Daoke Chuzi"
>>> name.istitle()
True
>>> name = "My name is daoKe chuzi"
>>> name.istitle()
False
14.检测字符串中所有的字母是否都为大写;是返回True否则返回False isupper()
>>> name = "MY NAME IS DAOKE CHUZI"
>>> name.isupper()
True
>>> names = "JAck Main"
>>> names.isupper()
False
15.指定的字符连接生成一个新的字符串;join()
>>> name = ("my","name","is","chuzi")
>>> "-".join(name)
'my-name-is-chuzi'
>>> names = "my name is daoke"
>>> "-".join(names)
'm-y- -n-a-m-e- -i-s- -d-a-o-k-e'
16.返回字符串长度;len()
>>> name = "Jack li"
>>> len(name)
7
17.返回一个原字符串左(右)对齐,默认使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串;ljust() rjust()
>>> name
'MY NAME IS DAOKE CHUZI'
>>> name.ljust(50)
'MY NAME IS DAOKE CHUZI '
>>> name.ljust(10)
'MY NAME IS DAOKE CHUZI'
>>> name.ljust(40)
'MY NAME IS DAOKE CHUZI '
>>> name.ljust(40,"*")
'MY NAME IS DAOKE CHUZI******************'
18.转换字符串中所有大写字符为小写;lower()
>>> name
'My NAME IS chuzi!!!'
>>> name.lower()
'my name is chuzi!!!'
>>> name.lower()
19.截掉字符串左(右、两边)边的空格或指定字符;两边strip()、左边lstrip()、右边rstrip()
>>> str
' this is string example....wow!!! '
>>> str.strip()
'this is string example....wow!!!'
>>> str.lstrip()
'this is string example....wow!!! '
>>> str.rstrip()
' this is string example....wow!!!'
20.把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次;replace()
>>> names
'abc is abc bcd is abc this abc'
>>> names.replace("abc","ABC")
'ABC is ABC bcd is ABC this ABC'
>>> names.replace("abc","ABC",3)
'ABC is ABC bcd is ABC this abc'
21.指定分隔符对字符串进行切片,如果参数num 有指定值,就会依照指定num个子分隔字符串;split()
>>> str
'this is string example....wow!!!'
>>> str.split()
['this', 'is', 'string', 'example....wow!!!']
>>> str.split("i",1)
['th', 's is string example....wow!!!']
>>> str.split("i",2)
['th', 's ', 's string example....wow!!!']
22.按照行分隔,返回一个包含各行作为元素的列表,将\n的参数值去除;splitlines()
[root@linux-node1#>> ~]#cat a.py
# !/bin/bash/env python3
# _*_coding:utf-8_*_
str = 'this is \nstring example....\nwow!!!'
print(str.splitlines())
print(str)
[root@linux-node1#>> ~]#python3 a.py
['this is ', 'string example....', 'wow!!!']
this is
string example....
wow!!!
23.检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False;可以指定下标的位置;startswith()
>>> str = "this is string example....wow!!!"
>>> str.startswith("this")
True
>>> str.startswith("this",2,8)
False
>>> str.startswith("is",5,8)
True
24.用于对字符串的大小写字母进行转换;swapcase()
>>> str = "this IS string example....WOW!!!"
>>> str.swapcase()
'THIS is STRING EXAMPLE....wow!!!'
25.所有单词都是以大写开始,其余字母均为小写;title()
>>> str = "this IS string example....WOW!!!"
>>> str.title()
'This Is String Example....Wow!!!'
26.将字符串中的小写字母转为大写字母;upper()
>>> str = "this IS string example....WOW!!!"
>>> str.upper()
'THIS IS STRING EXAMPLE....WOW!!!'
27.检查字符串是否只包含十进制字符;isdecimal()
>>> age = "2016"
>>> age.isdecimal()
True
>>> age = "2016 "
>>> age.isdecimal()
False
#使用strip去除空格后,继续使用isdecimal判断
>>> age.strip().isdecimal()
True
28.判断一个值,是不是指定的类型;isinstance(o,t)
name = "zhangsan"
age = 18
aihao = ["nv","eat"]
print(isinstance(name, str)) # 判断name是不是 字符串
print(isinstance(age, str)) # 判断age 是不是 字符串
print(isinstance(age, int))
print(isinstance(aihao,list)) # 判断aihao 是不是列表
输出:
True
False
True
True