zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python中常用的基础操作(1)——字符串

Python基础 操作 字符串 常用
2023-06-13 09:17:12 时间

流畅的数据分析离不开基础的巩固,本篇主要介绍了python中字符串的常用基础操作。内容有:字符串的替换、大小写转换、去除、截取、查找、格式化、分割

1 字符串中的常用操作

1

字符串的替换

字符串替换的语法为:str.replace()

共有三个参数:要替换的字符/字符串;要替换成的字符;替换次数(不传参数默认替换所有)

1.替换单个字符

str1 = 'apple apple'
new_str1 = str1.replace('a', 'A')  #将所有的a替换为A 
print(new_str1)

new_str2 = str1.replace('a', 'A', 1) #将第一个a替换为A
print(new_str2)

输出结果:

Apple Apple
Apple apple

2.替换多个字符

new_str1 = str1.replace('apple', 'Apple')  #替换所有的apple
print(new_str1)

new_str2 = str1.replace('apple', 'Apple', 1)  #替换第一个apple
print(new_str2)

输出结果:

Apple Apple
Apple apple

2

字符串大小写转换

函数有:title()、lower()、upper()、capitalize()、swapcase()

title:标题首字母大写

lower:全部转为小写

upper:全部转为大写

capitalize:第一个单词首字母大写,其余为小写

swapcase:大小写字母互相转化

示例:

str1 = 'hello World'
print(str1.capitalize())

输出结果:

Hello world

3

字符串去除

在日常编码过程中,我们通常会遇到将字符串开头或结尾的空格或其他符号去除,此时就可以使用字符串去除函数。

函数有:strip()、lstrip()、rstrip()、replace()

strip:去除首尾指定字符,不传参数默认去除空格

lstrip:去除开头指定字符,不传参数默认去除空格

rstrip:去除结尾指定字符,不传参数默认去除空格

replace:用法同1

示例:

str1 = '\n123456\n'
print(str1.strip('\n'))  #去除开头结尾的换行符

4

字符串截取

函数:str[起始位置:结束位置]

注:起始位置从0开始,位置可以为负数。

str1 = 'http://www.baidu.com'
print(str1[2:5]) #获取索引为2-4的字符
print(str1[:5]) #获取前5字符
print(str1[-5:]) #获取后5字符

结果如下:

tp:
http:
u.com

5

字符串查找

在一个字符串中,我们可能需要找出某个子字符串的位置索引,这就用到了字符串的查找。

函数:find()、rfind()、index()、rindex()、count()

find:查找字符串第一次出现的位置,若未查到,返回-1

rfind:查找字符串最后一次出现的位置

index:功能同find,但若未查到,抛出异常

rindex:功能同rfind,但若未查到,抛出异常

count:计算字符串出现的次数

示例:

str1 = 'hello world and python and java and html'
print(str1.find('and')) #查找第一次出现and的索引
print(str1.rfind('and')) #查找最后一次出现and的索引

6

字符串格式化

字符串格式化推荐使用format语法,format语法搭配字符串的{}一起使用。

其中{}的语法为{:abc},a为填充的字符(不填默认为空格),b为对齐方式(^居中对齐,<左对齐,>右对齐),字符长度,示例如下:

str1 = 'Welcome'
f1 = '{:*^20}'.format(str1)  #居中对齐,20个字符长度,用*填充    
print('{:0>06d}'.format(42))  #右对齐,6个字符长度,用0填充
print('{:0>10.3f}'.format(3.14156)) #右对齐,10个字符长度,保留三位小数,用0填充
print('{:,}'.format(123456789)) #以货币格式输出

结果如下:

******Welcome*******
000042
000003.142
123,456,789

7

字符串分割

1、按字符分割

将字符串每个字符都分割为列表形式。

函数:list(str)

str1 = 'apple'
print(list(str1))

结果如下:

['a', 'p', 'p', 'l', 'e']

2、按指定分隔符分割

函数:str.split(),若不传参数,默认按照空格分割

str1 = 'Hello world, hello friends'
print(str1.split())
print(str1.split(','))

结果如下:

['Hello', 'world,', 'hello', 'friends']
['Hello world', ' hello friends']

8

字符串拼接

1、字符串乘法

有时候我们需要将一个字符串复制多份,可以使用字符串乘法,示例如下:

str1 = 'apple 'print(str1*3)

结果如下:

apple apple apple

2、字符串拼接

普通的字符串拼接直接使用"+"即可将左右字符串连接在一起。


声明:本公众号的所有原创内容,在未经允许的情况下,不得用于商业用途,违者必究。