一、数据类型
- 字符串:str()
- 整数:int()
- 浮点数:float()
二、字符串
- 穿上单引号、双引号、三引号黄袍的内容就是字符串,无论引号里面内容是中文、英文、法文、数字、符号、甚至是火星文。
movie = '美国队长2'
name = 'The Winter Soldier'
price = "7.14"
word = '''≡(▔﹏▔)≡'''
print(movie)
print(name)
print(price)
print(word)
- 字符串, 江湖行话, 就是由一个个字符连接起来的组合, 你平时所见的字母、数字、汉字、符号都是字符。 字符串可以用来表示词、语句、甚至是数学公式。
name="我们强者就该无所畏惧"
anwser="那你为什么要跑?"
print(name)
print(anwser)
字符串类型必须有引号。
1. 字符串的处理函数
- len(X)函数:返回字符串X的长度。例:len(‘123’),结果为3
- hex(X)或oct(X):整数X的十六进制或八进制小写形式字符串。例:hex(425)的结果为0x1a9;oct(425的结果为0o651
- chr(U)函数:X为Unicode编码,返回其对应的字符。例:chr(X)的结果为Ʃ
- ord(X)函数:X为字符,返回其对应的Unicode编码。例:ord(‘Ʃ’)的结果为425
2. 字符串的处理方法
- str.lower()或str.upper():返回字符的副本,全部字符为小写或大写。
>>> print('i love you'.upper())
I LOVE YOU
>>> print('I LOVE you'.lower())
i love you
- str.split(sep=None):返回一个列表,由str根据sep被分隔的部分组成
>>> 'a,b,c'.split(',')
['a', 'b', 'c']
>>> 'i love you'.split(' ')
['i', 'love', 'you']
- str.count(sub):返回子串sub在str中出现的次数
>>> 'ikun is loving caixukun'.count('i')
4
>>> 'an apple a day'.count('an')
1
- str.replace(old,new):返回字符串副本,所有old子串被替换为new
>>> 'python, hello world'.replace('python','我不要')
'我不要, hello world'
>>> a = 'i love you'
>>> a.replace(' ','')
'iloveyou'
- str.center(width[,fillchar]):字符串str根据宽度width剧中,fillchar可选
>>> 'python'.center(20)
' python '
>>> 'python'.center(20,'-')
'-------python-------'
>>> '这个位置是剧中'.center(30,'=')
'===========这个位置是剧中============'
- str.strip(chars):从str中去掉其左侧和右侧chars中列出的字符
>>> p = '这个位置是居中'.c