Python的数据类型
1 字符串是什么
是Python的一种数据类型
是一系列字符
用引号括起来的都是字符串
"the Golden Snitch"
'Hippogriff'
2 字符串的操作
- 操作1 修改单词大小写
对变量调用方法
ball="the Golden Snitch"
print(ball.title()) #首字母大写
print(ball.upper()) #全部大写
print(ball.lower()) #全部小写
----------
The Golden Snitch
THE GOLDEN SNITCH
the golden snitch
①将字符串“the Golden Snitch”赋给变量「ball」
②调用函数print()
③对数据ball使用方法title()
- 方法是Python可对数据执行的操作
- ball.title()中,ball后面的「.」让Python对变量「ball」执行方法title()的操作
- 每个方法后面都跟着圆括号,因为方法通常需要额外的信息来完成其工作,这种信息是在圆括号内提供的
- 操作2 在字符串中使用变量
方法1:f字符串(3.6引入)
在字符串中插入变量的值
①引号前加上字母「f」
②引号内,要插入的变量名放在花括号「{}」内
behind="the Golden"
after="Snitch"
full=f"{behind} {after}" #引号内只有花括号
print(full)
----------
the Golden Snitch
behind="the Golden Snitch"
after="Hippogriff"
features=f"{behind} and {after}" #引号内有单纯的字符串
print(features)
----------
the Golden Snitch and Hippogriff
behind="the Golden Snitch"
after="Hippogriff"
features=f"{behind.title()} and {after.upper()}" #花括号内对变量调用方法
print(features)
----------
The Golden Snitch and HIPPOGRIFF
方法2:方法format()
behind="the Golden"
after="snitch"
full="{} {}".format(behind,after)
----------
the Golden snitch
- 操作3 在字符串中添加制表符和换行符
制表符和换行符的使用
print("the Golden Snitch")
print("\tthe Golden Snitch") #\t 制表符
print("\nthe Golden Snitch") #\n 换行符
----------
the Golden Snitch
the Golden Snitch
the Golden Snitch
- 操作4 删除字符串中的空白
对字符串调用方法strip()
favorite_animals="the Golden Snitch"
print(favorite_animals)
favorite_animals=" the Golden Snitch "
print(f"'{favorite_animals}'")
print(f"'{favorite_animals.rstrip()}'") #rstrip() 去掉字符串末端的空格
print(f"'{favorite_animals.lstrip()}'") #lstrip() 去掉字符串首端的空格
print(f"'{favorite_animals.strip()}'") #strip() 去掉字符串两边的空格
----------
the Golden Snitch
' the Golden Snitch '
' the Golden Snitch'
'the Golden Snitch '
'the Golden Snitch'