1. input().split()
功能:
input() 用于从用户输入中读取一行字符串。
split() 用于将字符串按指定分隔符分割成多个子字符串,并返回一个列表。
语法:
input().split([sep[, maxsplit]])
sep(可选):分隔符,默认为空白字符(空格、换行符等)。
maxsplit(可选):最大分割次数。如果未提供,则全部分割。
示例:
# 用户输入: "apple banana orange"
user_input = input().split()
print(user_input) # 输出: ['apple', 'banana', 'orange']
# 用户输入: "apple,banana,orange"
user_input = input().split(',')
print(user_input) # 输出: ['apple', 'banana', 'orange']
应用场景:
从用户输入中提取多个值(例如,多个数字或多个单词)。
2. input().strip()
功能:
input() 用于从用户输入中读取一行字符串。
strip() 用于去除字符串开头和结尾的指定字符(默认是空白字符,如空格、换行符 \n、制表符 \t )。
语法:
input().strip([chars])
chars(可选):指定要去除的字符。如果未提供,则默认去除空白字符。
示例:
# 用户输入: " hello world \n"
user_input = input().strip()
print(user_input) # 输出: "hello world"
# 用户输入: "xxxyyyhelloxxxyyy"
user_input = input().strip('xy')
print(user_input) # 输出: "hello"
应用场景:
清理用户输入的多余空白字符。
去除字符串开头或结尾的特定字符。
3. join()
功能:将列表中的字符串连接成一个字符串。
语法:
str.join(iterable)
示例:
fruits = ['apple', 'banana', 'orange']
result = ', '.join(fruits)
print(result) # 输出: "apple, banana, orange"
4. replace()
功能:替换字符串中的子字符串。
语法:
str.replace(old, new[, count])
示例:
text = "hello world"
result = text.replace('world', 'Python')
print(result) # 输出: "hello Python"
5. startswith()和 endswith()
功能:检查字符串是否以指定子字符串开头或结尾。
语法:
str.startswith(prefix[, start[, end]])
str.endswith(suffix[, start[, end]])
示例:
text = "hello world"
print(text.startswith('hello')) # 输出: True
print(text.endswith('world')) # 输出: True
6. find() 和 index()
功能:查找子字符串在字符串中的位置。
区别:
find():如果未找到子字符串,返回 -1。
index():如果未找到子字符串,抛出 ValueError异常。
语法:
str.find(sub[, start[, end]])
str.index(sub[, start[, end]])
示例:
text = "hello world"
print(text.find('world')) # 输出: 6
print(text.index('world')) # 输出: 6
7. lower()和upper()
功能:将字符串转换为小写或大写。
语法:
str.lower()
str.upper()
示例:
text = "Hello World"
print(text.lower()) # 输出: "hello world"
print(text.upper()) # 输出: "HELLO WORLD"
8. 综合示例
# 用户输入: " Apple, Banana, Orange "
user_input = input().strip() # 去除开头和结尾的空白字符
fruits = user_input.split(',') # 按逗号分割
fruits = [fruit.strip().lower() for fruit in fruits] # 去除每个水果名称的空白字符并转换为小写
# 输出处理后的水果列表
print(fruits) # 输出: ['apple', 'banana', 'orange']