第三章:字符串

1.介绍 

是一种用来表示文本的数据类型,由字符号或数值组成的一个连续序列

(1)定义

定义用处例子
单引号定义单行字符串'hello itcast'
双引号定义单行字符串"hello itcast"
三引号定义多行字符串

"""my name is itcast

my name is itcast"""

(2)转义

使用反斜杠“\”转义

print('let\'s learn Python')


let's learn Python

 2.格式化字符串

(1)%

format % values

(2)format()

str.format(values)

 (3)f-string

f('{变量名}') 或F('{变量名}')

3.查找与替换

(1)查找

find()可以查找字符串中是否包含子串,若包含则返回子串首次出现的位置,否则返回-1

str.find(sub[, start[, end]])

word = 't'
string = 'Python'
result = string.find(word)
print(result)

2

(2)替换

replace()可以将当前字符串中的指定子串替换成新的子串,并返回替换后的新字符串

str.replace(old, new[, count])

string = 'He said, "you have to go forward, ' \
'Then turn left, Then go forward, and Then turn right."'
# 指定替换两次
new_string = string.replace("Then", "then",2)
print(new_string)


He said, "you have to go forward, then turn left,
 then go forward, and Then turn right."

4.分隔与拼接

(1)分割

split()可以按照指定分隔符对字符串进行分割,该方法会返回由分割后的子串组成的列表

str.split(sep=None, maxsplit=-1)

string= "Hello, my name is Wang Hong"
# 以空格作为分割符,并分割2次
print(string.split(' ', 2))


['Hello,', 'my', 'name is Wang Hong']

(2)拼接

join()使用指定的字符连接字符串并生成一个新的字符串

str.join(iterable)


symbol = '*'
world = 'Python'
print(symbol.join(world))


P*y*t*h*o*n

还可以使用“+”拼接

"py" + "thon" = "python"

5.删除

6.对齐

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值