3 Python的数据类型——字符串

3 Python的数据类型——字符串,第1张

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'

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/876056.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存