列表推导式、字符串方法

目录

.upper() and .lower(): Convert a string to uppercase or lowercase.

.capitalize() and .title(): Capitalize the first letter of a string 、 capitalize each word in a string.

.strip(), .lstrip(), and .rstrip(): Remove whitespace characters from the beginning, end, or both sides of a string.

.find() and .index(): Find the index of a substring within a string. find() returns -1 if not found, while index() raises an error.

.replace( ): Replace occurrences of a substring with another substring.

.startswith(prefix) and .endswith(suffix): Check if a string starts or ends with a specific substring.

.count(substring): Count the occurrences of a substring within a string.

.split(separator): Split a string into a list of substrings based on a separator.

.join(iterable): Join elements of an iterable (like a list) into a single string using the string as a separator.


列表推导式(List Comprehensions)是 Python 中用于快速创建列表的一种紧凑且可读性强的方式。

列表推导式的一般形式为:

[expression for item in iterable]
  • expression 是对每个 item 的计算结果。
  • item 是迭代过程中的每个元素。
  • iterable 是一个可迭代对象,比如列表、元组、集合、字典等。
[expression for item in iterable if condition]

这样就可以根据 conditioniterable 中的元素进行筛选,只有满足条件的元素才会被包含在最终的列表中。

# 创建一个包含1到10的平方的列表
squared = [x**2 for x in range(1, 11)]

# 使用条件过滤,仅包含能被3整除的元素
divisible_by_three = [x for x in range(1, 11) if x % 3 == 0]

# 列表推导式可以同时存在if和else
new_nums = [x if x % 2 == 0 else x * 2 for x in nums]

这些列表推导式提供了一种简洁、高效的方法来创建新的列表,并且在代码中能够更清晰地表达意图。

总结:

列表推导式返回一个迭代器,可以用next()方法访问元素。上述代码因为将列表推导式放在了[ ]中转换成了列表,所以最终的输出是一个列表,列表推导式只返回迭代器。

.upper() and .lower(): Convert a string to uppercase or lowercase.

my_string = "Hello World"
print(my_string.upper())  # Output: HELLO WORLD
print(my_string.lower())  # Output: hello world

.capitalize() and .title(): Capitalize the first letter of a string 、 capitalize each word in a string.

text = "hello world"
capitalized_text = text.capitalize()# 句子的首字母大写
print(capitalized_text)  # Output: "Hello world"

text = "hello world"
title_text = text.title()# 句子中每个单词的首字母大写
print(title_text)  # Output: "Hello World"


.strip(), .lstrip(), and .rstrip(): Remove whitespace characters from the beginning, end, or both sides of a string.

whitespace_string = "  Hello  "
print(whitespace_string.strip())   # Output: "Hello"
print(whitespace_string.lstrip())  # Output: "Hello  "  
print(whitespace_string.rstrip())  # Output: "  Hello"

text = "18500"
trimmed_text = text.rstrip('0')# 移除指定字符
print(trimmed_text)  # Output: "185"

.find() and .index(): Find the index of a substring within a string. find() returns -1 if not found, while index() raises an error.

my_string = 'Hello World!'
print(my_string.find('lo'))   # Output: 3
print(my_string.index('lo'))  # Output: 3

.replace( ): Replace occurrences of a substring with another substring.

count表示替换几个(选填),这个参数不写就是都替换,写数字几就是替换前几个

text = "Hello World"
new_text = text.replace('o', 'X')#o全部替换为X

print(new_text)  # Output: "HellX WXrld"

text = "Hello World"
new_text = text.replace('o', 'X', 1)# 把前一个替换

print(new_text)  # Output: "HellX World"

text = "Hello Hello Hello"
new_text = text.replace('Hello', 'Hi', 2)# 把前两个替换

print(new_text)  # Output: "Hi Hi Hello"

.startswith(prefix) and .endswith(suffix): Check if a string starts or ends with a specific substring.

text = "Hello World"

print(text.startswith('Hello'))  # Output: True
print(text.endswith('World'))   # Output: True

.count(substring): Count the occurrences of a substring within a string.

my_string = 'Hello World'
print(my_string.count('l'))  # Output: 3

.split(separator): Split a string into a list of substrings based on a separator.

my_string = 'Hello World'
splitted_string = my_string.split(' ')
print(splitted_string)  # Output: ['Hello', 'World']


my_string = "apple,banana,orange,grape"
fruits = my_string.split(',', 2)  # Performs split at ',' up to 2 times
print(fruits)  # Output: ['apple', 'banana', 'orange,grape']

.join(iterable): Join elements of an iterable (like a list) into a single string using the string as a separator.

new_string = '-'.join(['Hello', 'World'])
print(new_string)  # Output: Hello-World

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值