python 之字符串的使用

作者:神秘网友 发布时间:2021-02-23 17:20:14

python 之字符串的使用

在python中,字符串是最常用的数据类型,通常由单引号(' ')、双引号(" ")、三重引号(''' ''',""" """)引起来。

# 字符串的创建
str1 = "hello world"
str2 = 'sunlight'
str3 = '''On a new day,
the sun rises in the East
'''
str4 = """On a new day,
the sun rises in the East"""
str5 = "What's this"

使用单引号、双引号、三重引号创建的字符串是无区别的,验证如下

str1 = 'sunlight'
str2 = "sunlight"
str3 = """sunlight"""
str4 = '''sunlight'''
print(str1 == str2 == str3 == str4)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
True

Process finished with exit code 0

三重引号的使用场景一般用于类、函数等注释,或者定义含有多行的字符串

字符串是一个由独立字符组成的序列,意味着可以

1.获取字符串长度

# 获取字符串长度
str1 = 'sunlight'
print(len(str1))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
8

Process finished with exit code 0

2、通过下标读取其中的某个字符

# 通过下标读取字符
str1 = 'sunlight'
print(str1[1])
print(str1[0])
print(str1[-1])

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
u
s
t

Process finished with exit code 0

3、通过切片方式读取字符串片段

# 切片方式读取片段
str1 = 'sunlight'
print(str1[2:4])
print(str1[-4:-1])

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
nl
igh

4.字符串拼接

# 字符串拼接
str1 = 'sunlight'
str2 = 'hello '

print(str2 + str1)
print(str1[2:4] + str2[1:3])

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
hello sunlight
nlel

5.遍历字符串

# 遍历字符串
str1 = 'sunlight'
for i in str1:
    print(i)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
s
u
n
l
i
g
h
t

Process finished with exit code 0

python中的转义字符:就是用反斜杠开头的字符串,表示特定的意义,常见的转义字符如表中所示

# 转义示例
str4 = """On a new day,the sun rises in the East"""
str5 = 'what\t do\b you \v do'
str6 = 'What\'s this'
str7 = "It's \"cat\""
print(str4, "\n", str5, "\n", str6, "\n", str7)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
On a new day,the sun rises in the East 
 what     d you  do 
 What's this 
 It's "cat"

Process finished with exit code 0

python中字符串常用的运算符

# 运算符示例
str1 = 'sun' + 'light '
s = "r" in str1
t = "r" not in str1
w = r'\n' + R'\t'
z = 3.14159

print(str1, str1*3 + "\n", s, t, "\n" + w)
print("Π的值是%s:" % z)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight  sunlight sunlight sunlight 
 False True 
\n\t
Π的值是3.14159:

Process finished with exit code 0

改变字符串:

在数组中可以通过下标直接更改值,但是字符串中同样的操作会提示“'str' object does not support item assignment”

# 变更字符串
str1 = 'sunlight'
str1[0] = "D"
print(str)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
Traceback (most recent call last):
  File "D:/demo/str_1.py", line 52, in module
    str1[0] = "D"
TypeError: 'str' object does not support item assignment

Process finished with exit code 1

通过创建新的字符串间接更改

# 创建新的字符串间接更改
str1 = 'sunlight'
s = "S" + str1[1:]
t = str1.replace("s", "S")
str1 = s
print(str1, t)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
Sunlight Sunlight

Process finished with exit code 0

通过符号 += 更改

# 通过 += 符号 更改
str1 = 'sun'
str1 += 'light'
print(str1)

info = "start "
for s in str1:
    info += s
print(info)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
start sunlight

Process finished with exit code 0

python中的字符串格式化

字符串格式化可以理解为将实际值插入模板中

# 使用%实现字符串格式化
student = {"张三": 19, "李四": 20, "王五": 20}
for info in student:
    print("学生 %s的年龄为 %s" % (info, student[info]))

# 使用string.format()方法实现字符串格式化
prices = {"apple": 8.99, "banana": 6.99, "orange": 7.99}
for price in prices:
    print("水果 {}的单价为 {}".format(price, prices[price]))


"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
学生 张三的年龄为 19
学生 李四的年龄为 20
学生 王五的年龄为 20
水果 apple的单价为 8.99
水果 banana的单价为 6.99
水果 orange的单价为 7.99

Process finished with exit code 0

常用字符串内建函数

string.split(sep, maxsplit):maxsplit给定值max,sep在字符串中出现的次数为num, 且给定的值0= max =num,以sep作为分隔符进行切片字符串,则分割max+1个字符串,若max不传(不传时默认为-1)或者传入的值大于num,则默认分割num+1个字符串,并返回由字符串组成的数组

str1 = 'sunlight'
r = str1.split("l")     # maxsplit不传时,默认为-1,返回1+1个字符
s = str1.split("l", 0)  # maxsplit传入0则返回0+1个字符
t = str1.split("l", 3)  # maxsplit传入值大于分隔符出现的次数,返回1+1个字符
w = str1.split()        # sep 不传时,默认为空白字符
print(r, "\n", s, "\n", t, "\n", w)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
['sun', 'ight'] 
 ['sunlight'] 
 ['sun', 'ight'] 
 ['sunlight']

Process finished with exit code 0

string.strip(chars): 从起始至末尾去掉指定的chars,若不指定默认去除字符串左边空格和末尾空格(相当于执行了string.lstrip()和string.rstrip()),并返回去除后的字符串

# 常用内建函数
str1 = ' sunlight '
t = str1.strip()
w = str1.strip("t ")
print(t)
print(str1)
print(w)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
 sunlight 
sunligh

Process finished with exit code 0

string.rstrip(chars):右起去掉指定的chars,若不指定默认去除字符串末尾空格,并返回去除后的字符串

# 常用内建函数
str1 = '    sunlight '
x = str1.rstrip()
y = str1.rstrip("t ")
print(str1)
print(x)
print(y)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
    sunlight 
    sunlight
    sunligh

Process finished with exit code 0

string.lstrip(chars):左起删除指定的chars,若不指定默认去除字符串左边空格,并返回去除后的字符串

# 常用内建函数
str1 = '    sunlight '
z = str1.lstrip()
t = str1.lstrip(' su')
print(z)
print(t)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight 
nlight 

Process finished with exit code 0

string.find(sub, start, end):检测字符串中是否包含指定字符串sub,如果包含则返回首次出现的位置索引值,否则返回-1,start、end非必填,若指定start、end则在指定范围内查找

# 常用内建函数
str1 = 'sunlightn'
a = str1.find("n")  # 字符串中含有n,返回首次出现的位置索引值2
b = str1.find("n", 3)  # 从索引为3开始检测,返回首次出现的位置索引值8
c = str1.find("n", 0, 2)  # 从索引[0, 2)开始检测,检测不到返回-1
print(a, b, c)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
2 8 -1

Process finished with exit code 0

string.rfind(sub, start, end):用法与find类似,区别在返回指定sub最后出现的位置索引值,否则返回-1

# 常用内建函数
str1 = 'sunlightn'
e = str1.rfind("n")  # 字符串中含有n,返回最后出现的位置索引值8
f = str1.rfind("n", 0, 3)  # 从索引[0, 3)开始检测
print(e, f)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
8 2

Process finished with exit code 0

string.count(sub, start, end):返回指定sub在字符串中出现的次数,若指定start、end则在指定范围内统计

# 常用内建函数
str1 = '    sunlight '
j = str1.count(" ")
k = str1.count(" ", 2, 9)
print(j, k)


"D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
5 2

Process finished with exit code 0

python 之字符串的使用 相关文章

  1. 数据迁移时报错——django.db.migrations.exceptions.NodeNotFoundError: Migration apitest.0001_initial dependencies reference nonexistent parent node (product, 0001_initial)

    执行python manage.py makemigrations时出现以下错误 D:\autotestplatpython manage.py makemigrationsTraceback (most recent call last): File "manage.py", line 21, in module main() File "manage.py", line 17, in main execute_from_command_line(sys

  2. python之openpyxl模块

    Python_Openpyxl 1. 安装 pip install openpyxl 2. 打开文件 ① 创建 from openpyxl import Workbook # 实例化wb = Workbook()# 激活 worksheetws = wb.active ② 打开已有 from openpyxl import load_workbook wb2 = load_workbook('文件名称.xlsx') 3. 储

  3. Vuex使用流程

    1.可以devDependencies安装:npm installvuex -D "vuex":"^3.6.2"2.创建store文件src/store/index.js或者src/store.js import Vue from "vue";import Vuex from "vuex";Vue.use(Vuex);import travel from "./modules/travel";import goods from "./modules/g

  4. 官方文档 - 使用GitBook和Typora生成类似官方文档

    本文主要介绍我使用的GitBook + Typora + Git(服务器),来编写类似的官方文档: 一、GitBook介绍 GitBook 是一个基于 Node.js 的命令行工具,可使用 Github/Git 和 Markdown来制作精美的电子书,GitBook 并非关于 [Git]的教程。 GitBook是一款文档编辑工具。它

  5. springboot 如何使用自定义注解+aop实现全局日志持久化操作

    1.自定一个注解 package com.hc.manager.common.aop.annotation; import java.lang.annotation.*; /** * LogAnnotation * * @author summer.chou * @version V1.0 * @date 2020年3月18日 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME

  6. 【tf.wiki】02-TensorFlow基础示例:线性回归 (分别使用np和ts进行梯度下降预测房价+反归一化还原数据)

    知识补充 举例函数\(Z=f(X,Y)\): 偏导数 将X固定,Z的增量除以Y的增量,我们称之为Z对Y的偏导数 同理,我们保持Y值不变,Z值仅随X值改变,Z的增量除以X的增量,我们称之为Z对X的偏导数 梯度 每个点都有一个箭头来表示Z对X的偏导数,每个点都有一个箭头来表

  7. git使用笔记

    记录一下学习git的代码 git官方使用文档 1.安装git Windows系统Git安装教程(详解Git安装过程) # 任意文件打开 git bash here git --version # 检查安装版本 git config --list # 检查配置信息 2.初始配置 git config --global user.name 'your_name' git c

  8. 如何用python自动编写《赤壁赋》word文档

    目录 前言 安装-python-docx 一、自动编写《赤壁赋》 准备数据 新建文档 添加标题 添加作者 添加朝代 添加图片 添加段落 保存word文档 二、自动提

  9. PHP mjpeg 连续图片格式生成

    使用PHP生产mjpeg格式图片。 在HTML直接在img的src访问。 img src="./mjpeg2.php" php// https://images1.tqwba.com/20210223/graxkbkopw3date_default_timezone_set("PRC");error_reporting(E_ALL ~E_NOTICE);// Used to separate multipart$boundary = "sp

  10. KVM 搭建以及使用

    KVM 搭建 一、准备环境 操作系统:Centos7 磁盘:100G 二、部署操作 2.1、关闭selinux 和 firewalld \cp /etc/selinux/config /etc/selinux/config.baksed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/configsystemctl disable firewalldsystem

每天更新java,php,javaScript,go,python,nodejs,vue,android,mysql等相关技术教程,教程由网友分享而来,欢迎大家分享IT技术教程到本站,帮助自己同时也帮助他人!

Copyright 2020, All Rights Reserved. Powered by 跳墙网(www.tqwba.com)|网站地图|关键词