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")
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() 将字符串分割
s3 = 'helloWorlD'
s4 = s3.capitalize()
s4
'Helloworld'
'{} {}'.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
s4 = "I am a teacher 你 好"
s4.split()
['I', 'am', 'a', 'teacher', '你', '好']
"nihao huanle".endswith('e')
True
注意点
int('45')+45
90
s = 'hello'
s = 'world'
print("I am %s,I am %d years old"%("huanle",25))
I am huanle,I am 25 years old