【Python基础】一些输入input的写法

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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值