python将数组字符串转为列表_Python 基础知识全篇-字符串列表

7ad95950641930ac7bfe4bfa35669d13.png

现在我们已经对列表有了一定的了解。回头看一下字符串,会发现它不过是字符的集合,即包含一系列字符的列表。它们背后的工作原理是如此的相似,接下来让我们一探究竟吧。

作为字符列表的字符串

就像列表一样,我们可以对一个字符串作循环操作。如下所示:

message = "Hello!"

for letter in message:
    print(letter)

我们可以利用一个字符串生成一个列表。这个列表会为每个字符生成一个列表元素。如下所示:

message = "Hello world!"

message_list = list(message)
print(message_list)

切割字符串

就像列表中访问元素一样,我们可以利用字符位置访问字符串中的字符。如下所示:

message = "Hello World!"
first_char = message[0]
last_char = message[-1]

print(first_char, last_char)

进一步扩展切割,如下所示:

message = "Hello World!"
first_three = message[:3]
last_three = message[-3:]

print(first_three, last_three)

查找子串

现在你或许发现索引在字符串中意味着什么。我们可以在字符串中查询字串。字串就是在字符串中出现的一系列相邻字符集合。

你可以用关键字 in 查询某字串是否在字符串中。如下所示:

message = "I like cats and dogs."
dog_present = 'dog' in message
print(dog_present)

如果你想知道字串出现的位置,可以使用find()方法。它会告诉你字串在字符串中的开始位置。如下所示:

message = "I like cats and dogs."
dog_index = message.find('dog')
print(dog_index)

需要注意的是,这个方法只会返回第一个出现的字串的开始位置,如果有多个字串,余下的字串位置会被忽略。如下所示:

message = "I like cats and dogs, but I'd much rather own a dog."
dog_index = message.find('dog')
print(dog_index)

如果你想知道最后一个出现的字串的初始位置,可以使用rfind()方法。如下所示:

message = "I like cats and dogs, but I'd much rather own a dog."
last_dog_index = message.rfind('dog')
print(last_dog_index)

替换子串

你可以使用 replace() 函数用指定字符串替代字符串中的子串。函数中包含两个参数,第一个参数是想要替换的子串,第二个参数为替代字符串。如下所示:

message = "I like cats and dogs, but I'd much rather own a dog."
message = message.replace('dog', 'snake')
print(message)

子串计数

如果你想计算某一子串在字符串中出现了多少次,可以用 count() 函数来实现。如下所示:

message = "I like cats and dogs, but I'd much rather own a dog."
number_dogs = message.count('dog')
print(number_dogs)

分裂字符串

字符串可以按照某一字符分裂成若干个子串。如果一个字符串包含一个简单的句子,就可以按照空格将字符串分裂成若干子串。split() 函数分裂字符串,并返回一个子串列表。它包含一个参数,字符串就按照这个参数代表的字符分割。如下所示:

message = "I like cats and dogs, but I'd much rather own a dog."
words = message.split(' ')
print(words)

动手试一试

Listing a Sentence

  • 在一个变量中存储一条语句。用 for 循环打印其中的每个字符。

Sentence List

  • 在一个变量中存储一条语句。利用这条语句创建一个列表。打印列表。

Sentence Slices

  • 在一个变量中存储一条语句。打印出前五个,中间连续五个,最后五个字符。

Finding Python

  • 在一个变量中存储一条语句。确保至少包含两个 Python 单词。
  • 使用关键字 in 证明这条语句中包含 Python。
  • 使用 find() 函数找出 Python 第一次出现的位置。
  • 使用 rfind() 函数找出 Python 最后一次出现的位置。
  • 使用 count() 函数计算 Python 出现的次数。
  • 使用 split() 函数分裂你的字符串语句。
  • 使用 replace() 函数将 Python 代替为 Ruby。
# Ex : Listing a Sentence

# put your code here
# Ex : Sentence List

# put your code here
# Ex : Sentence Slices

# put your code here
# Ex : Finding Python

# put your code here
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值