欢迎访问宙启技术站
智能推送

Python函数之字符串和列表常用操作及示例

发布时间:2023-07-01 14:25:26

Python中的字符串和列表是常用的数据类型,并且提供了丰富的操作方法。下面列举了一些常用的字符串和列表操作,并给出了相应的示例代码。

1. 字符串常用操作

- 长度:通过len()函数可以获取字符串的长度。

     s = "Hello, world!"
     print(len(s))  # 输出:13
     

- 连接:使用加号(+)操作符可以将两个字符串连接起来。

     s1 = "Hello, "
     s2 = "world!"
     print(s1 + s2)  # 输出:Hello, world!
     

- 分割:使用split()方法可以将字符串按照指定的分隔符进行分割,并返回一个列表。

     s = "Hello, world!"
     print(s.split())  # 输出:['Hello,', 'world!']

     s = "apple,banana,orange"
     print(s.split(","))  # 输出:['apple', 'banana', 'orange']
     

- 替换:使用replace()方法可以将字符串中指定的子串替换成新的子串。

     s = "Hello, world!"
     print(s.replace("world", "Python"))  # 输出:Hello, Python!
     

- 查找:使用find()方法可以查找字符串中指定的子串,并返回其 次出现的索引位置。如果找不到,则返回-1。

     s = "Hello, world!"
     print(s.find("world"))  # 输出:7
     print(s.find("Python"))  # 输出:-1
     

2. 列表常用操作

- 长度:通过len()函数可以获取列表的长度。

     lst = [1, 2, 3, 4, 5]
     print(len(lst))  # 输出:5
     

- 连接:使用加号(+)操作符可以将两个列表连接起来。

     lst1 = [1, 2, 3]
     lst2 = [4, 5]
     print(lst1 + lst2)  # 输出:[1, 2, 3, 4, 5]
     

- 添加元素:使用append()方法可以在列表的末尾添加新的元素。

     lst = [1, 2, 3]
     lst.append(4)
     print(lst)  # 输出:[1, 2, 3, 4]
     

- 删除元素:使用remove()方法可以删除列表中的指定元素。如果有多个相同的元素,则只删除 个。

     lst = [1, 2, 3, 4, 5]
     lst.remove(3)
     print(lst)  # 输出:[1, 2, 4, 5]
     

- 切片:使用切片操作可以获取列表的指定部分。切片的语法是start:stop:step,其中start表示起始索引,stop表示结束索引(不包括在内),step表示步长。

     lst = [1, 2, 3, 4, 5]
     print(lst[1:4])  # 输出:[2, 3, 4]
     print(lst[::2])  # 输出:[1, 3, 5]
     

- 排序:使用sort()方法可以对列表进行排序。默认是按照升序进行排序,可以通过传入reverse=True参数进行降序排序。

     lst = [3, 1, 4, 2, 5]
     lst.sort()
     print(lst)  # 输出:[1, 2, 3, 4, 5]

     lst.sort(reverse=True)
     print(lst)  # 输出:[5, 4, 3, 2, 1]
     

以上是字符串和列表常用操作的一些示例,它们可以满足日常编程中的大部分需求。当然,Python的字符串和列表操作远不止这些,还有很多其他功能可以探索和使用。