Python基础 学习笔记(二)字符串操作

这篇博客主要介绍了Python字符串的基础和核心操作,包括字符串连接、重复、长度计算,以及字符串的分割、拼接、替换方法。还特别提到了如何更改字符串的大小写以及处理空格,如strip、lstrip和rstrip函数的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基础操作

1、字符串连接

a = 'hello' + 'python'
a
'hellopython'

2、字符串重复多遍

a*3
'hellopythonhellopythonhellopython'

3、字符串长度

len(a)
11

二、核心操作

1、字符串分割

a = '1 2 3 4 5'
a.split()
['1', '2', '3', '4', '5']
b = '1,2,3,4,5'
b.split(',')
['1', '2', '3', '4', '5']

2、字符串拼接

a_str = ' '
a_str.join(a)
'1   2   3   4   5'

3、字符串替换

a = 'hello python'
a.replace('python','world')
'hello world'

注意:此时如果再输出a依然是hello python,如果想保留变化,就要新命名变量如:

b = a.replace('python','world')
b
'hello world'

4、更改大小写

c = b.upper()
d = c.lower()
c,d
('HELLO WORLD', 'hello world')

5、空格处理

a = '         hello python       '
b = a.strip()
c = a.lstrip()
d = a.rstrip()
b,c,d
('hello python', 'hello python       ', '         hello python')

strip函数可以去除两边空格,lstrip函数可以去除左边空格,rstrip函数可以去除右边空格

6、顺序

'{} {} {}'.format('a','b','c')
'a b c'
'{2} {1} {0}'.format('a','b','c')
'c b a'
'{a} {b} {c}'.format(a=10,b=20,c=30)
'10 20 30'
a = 'the result is :'
b = 123
c = 456
result = '%s %f %d' %(a,b,c)
result
'the result is : 123.000000 456'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值