03-python字符串

s1 = "hello"
s2 = "world"
s1+' '+s2
'hello world'
s1*3
'hellohellohello'
s1[:]
'hello'
s1[4]
'o'
s1[1:4]
'ell'
len(s1)
5

常用的字符串的转义:

\\ 反斜杠(保留一个)

\’ 单引号(保留’)

\b 退格

\n 换行

\t 水平制表符

print("hello\\world")#反斜杠
hello\world
print("hello\'world")#单引号
hello'world
print("hello\bworld")#退格字母w将o掩盖住了
helloworld
print("hello\nworld")#换行
hello
world
print("hello\tworld")#水平制表符
hello	world

字符串的方法

(1)capitalize() 把字符串的第一个字符大写

(2)format() 格式化字符串

(3)lower() 将字符串中的大写转换为小写

(4)upper() 将字符串中的小写转换为大写

(5)lstrip() 删除字符串左边的空格

(6)rstrip() 删除字符串右边的空格

(7)find() 查找

(8)split() 将字符串分割

# capitalize()
s3 = 'helloWorlD'
s4 = s3.capitalize()
s4
'Helloworld'
# format()
'{} {}'.format("你好","欢乐")

'你好 欢乐'
'{0} {1}'.format('你好','欢乐')
'你好 欢乐'
'{0} {0}'.format('你好','欢乐')
'你好 你好'
'{1} {0}'.format('你好','欢乐')
'欢乐 你好'
s4 = s3.lower()
s4
'helloworld'
s4.upper()
'HELLOWORLD'
s4 = "  "+s4
s4
'  helloworld'
s4.lstrip()

'helloworld'
s4 = 'xxxxxHELLOxxxxx欢乐'
s4.find('欢乐')
15
#split()方法
s4 = "I am a teacher 你 好"
s4.split()
['I', 'am', 'a', 'teacher', '你', '好']
# endwith()方法
"nihao huanle".endswith('e')
True

注意点

#字符串转换工具
int('45')+45
90
#字符串不允许修改:
s = 'hello'
s = 'world'
# s[0] = 'E'#就会报错
#字符串的格式化表达

print("I am %s,I am %d years old"%("huanle",25))
I am huanle,I am 25 years old

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值