Python学习第3天——字符串、列表

Python学习第3天

1、字符串

1.1、python 中的字符串字面量由单引号或双引号括起。‘hello’ 等同于 “hello”。

print("Hello")
print('Hello')

1.2、通过使用变量名称后跟等号和字符串,可以把字符串赋值给变量:

a = "Hello"
print(a)

1.3、像许多其他流行的编程语言一样,Python 中的字符串是表示 unicode 字符的字节数组。
但是,Python 没有字符数据类型,单个字符就是长度为 1 的字符串。
方括号可用于访问字符串的元素。

a = "Hello, World!"
print(a[1])

裁切
您可以使用裁切语法返回一定范围的字符。
指定开始索引和结束索引,以冒号分隔,以返回字符串的一部分。

b = "Hello, World!"
print(b[2:5])

负的索引

b = "Hello, World!"
print(b[-5:-2])

字符串长度

a = "Hello, World!"
print(len(a))

字符串方法
strip() 方法删除开头和结尾的空白字符:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

lower() 返回小写的字符串:

a = "Hello, World!"
print(a.lower())

upper() 方法返回大写的字符串:

a = "Hello, World!"
print(a.upper())

replace() 用另一段字符串来替换字符串:

a = "Hello, World!"
print(a.replace("World", "Kitty"))

split() 方法在找到分隔符的实例时将字符串拆分为子字符串:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

检查字符串
如需检查字符串中是否存在特定短语或字符,我们可以使用 in 或 not in 关键字
检查以下文本中是否存在短语 “ina”:

txt = "China is a great country"
x = "ina" in txt
print(x)

字符串格式
我们可以使用 format() 方法组合字符串和数字!
format() 方法接受传递的参数,格式化它们,并将它们放在占位符 {} 所在的字符串中:
字符串方法
字符串说明

2、列表

类似于C++数组但功能更加强大

创建列表

thislist = ["apple", "banana", "cherry"]
print(thislist)

访问项目

thislist = ["apple", "banana", "cherry"]
print(thislist[1])

负的索引
打印列表的最后一项:

thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

索引范围
返回第三、第四、第五项:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

负索引的范围
此例将返回从索引 -4(包括)到索引 -1(排除)的项目:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

更改项目值
更改第二项:

thislist = ["apple", "banana", "cherry"]
thislist[1] = "mango"
print(thislist)

遍历列表

逐个打印列表中的所有项目:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

检查项目是否存在
检查列表中是否存在 “apple”:

thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

列表方法
来自W3C

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值