一、字符串的使用
可以使用引号( ' 或 " 或“”)来创建字符串,python中单引号和双引号使用完全相同。
三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
'hello world'
>>> str2 = "hello world"
知识兔二、使用转义字符 \
2.1 常用的几种用法
- 在行尾时(\),续行符,实现多行语句;
- \'(\"),单引或双引;
- \n,换行;
- \r,回车;
- \000,空
2.2 使用r可以让反斜杠不发生转义
print ("this is a string \n")
this is a string
>>> print (r"this is a srting \n")
this is a srting \n
知识兔三、字符串运算符
字符串连接符:+
'hello world'
>>> str2 = "hello world"
>>> print(str1+str2)
hello worldhello world
>>> print(str1+' '+str2)
hello world hello world
知识兔重复输出字符串:*
print(str1*2)
hello worldhello world
>>> print(str1*3)
hello worldhello worldhello world
知识兔in/not in
成员运算符 - 如果字符串中包含给定的字符返回 True(或者不包含返回True)
四、字符串格式化
%s:输出字符串
%d:输出int类型
%f:输出浮点数类型
%x:输出16进制类型
"hello world"
print("%s" %hw)
知识兔Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置'world hello world'
知识兔五、字符串截取
#!/usr/bin/python
str = 'hello world'
print (str) # 输出字符串 hello world
print (str[0:-1]) # 输出第一个到倒数第二个 hello worl
print (str[0]) # 输出第一个字符 h
print (str[2:5]) # 输出从第三个开始到第五个字符 llo
print (str * 2) # 输出字符串2次 hello worldhello world
print (str + 'add') # 连接字符串 hello worldadd
知识兔六、字符串常用函数
6.1 str.index()
根据指定数据查找对应的下标:
'hello'
>>> my_str.index('e')
1
>>>
>>> my_str.index('l')
2 #(为什么是2不是3)
知识兔6.2 str.find() (同index)
'e')
1
知识兔find和index的区别:find如果没有找到指定的数据那么返回的结果是-1,index如果没有找到指定数据返回的结果报错。
'f')
-1
>>> my_str.index('f')
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
my_str.index('f')
ValueError: substring not found
知识兔6.3 统计字符串的长度len(str)
len(my_str)
>>> print(result)
5
知识兔6.4 统计某个字符出现的次数str.count()
'l')
>>> print(result)
2
知识兔6.5 替换指定数据str.replace()
'l','x')
>>> print(result)
hexxo
知识兔6.6 分隔数据str.split()
'e')
['h', 'llo']
知识兔6.7 判断是否以指定数据开头str.startswith()(结尾endswith)
'http://www.baidu.com'
>>> result = my_url.startswith('http')
>>> print(result)
True
知识兔6.7 根据指定字符串连接数据.join(str)
以指定字符串作为分隔符,将 str 中所有的元素(的字符串表示)合并为一个新的字符串
'abc'
>>> result = '-'.join(my_str)
>>> print(result)
a-b-c
>>> result = ' '.join(my_str)
>>> print(result)
a b c
知识兔