python字符串

时间:2019-09-23
本文章向大家介绍python字符串,主要包括python字符串使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、字符串的使用

可以使用引号( ' 或 " 或“”)来创建字符串,python中单引号和双引号使用完全相同。

三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。

>>> str1 = 'hello world'
>>> str2 = "hello world"

二、使用转义字符 \

2.1 常用的几种用法

  1. 在行尾时(\),续行符,实现多行语句;
  2. \'(\"),单引或双引;
  3. \n,换行;
  4. \r,回车;
  5. \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

三、字符串运算符

字符串连接符:+

>>> str1 = '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进制类型

hw = "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()

根据指定数据查找对应的下标:

>>> my_str = 'hello'
>>> my_str.index('e')
1
>>> 
>>> my_str.index('l')
2     #(为什么是2不是3)

6.2 str.find() (同index)

>>> my_str.find('e')
1

find和index的区别:find如果没有找到指定的数据那么返回的结果是-1,index如果没有找到指定数据返回的结果报错。

>>> my_str.find('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)

>>> result = len(my_str)
>>> print(result)
5

6.4 统计某个字符出现的次数str.count()

>>> result = my_str.count('l')
>>> print(result)
2

6.5 替换指定数据str.replace()

>>> result = my_str.replace('l','x')
>>> print(result)
hexxo

6.6 分隔数据str.split()

>>> my_str.split('e')
['h', 'llo']

6.7 判断是否以指定数据开头str.startswith()(结尾endswith)

>>> my_url = 'http://www.baidu.com'
>>> result = my_url.startswith('http')
>>> print(result)
True

6.7 根据指定字符串连接数据.join(str)

以指定字符串作为分隔符,将 str 中所有的元素(的字符串表示)合并为一个新的字符串

>>> my_str = 'abc'
>>> result = '-'.join(my_str)
>>> print(result)
a-b-c
>>> result = ' '.join(my_str)
>>> print(result)
a b c

原文地址:https://www.cnblogs.com/cp-linux/p/11575638.html