【问题标题】:Is there a function that makes python read only some parts of a string and execute an operation有没有一个函数可以让python只读取字符串的某些部分并执行操作
【发布时间】:2022-12-05 07:03:07
【问题描述】:
我是编程初学者,我试图让我的 python 只读取字符串的前 3 位数字,并根据字符串的前 3 位数字打印答案。
我试过了
如果 str[1,2,3] = 080:
打印(...)
elif str[123] =090:
打印(,,,)
【问题讨论】:
标签:
string
indexing
ef-code-first
【解决方案1】:
以下是如何在 Python 中实现此目的:
# Store the string in a variable
string = "Hello world"
# Get the first three characters of the string
first_three_chars = string[:3]
# Check if the first three characters are "080"
if first_three_chars == "080":
print("The first three characters are 080")
elif first_three_chars == "090":
print("The first three characters are 090")
else:
print("The first three characters are not 080 or 090")
在这段代码中,我们使用 string[:3] 语法来获取字符串的前三个字符。然后,我们使用 if 和 elif 语句来检查前三个字符是“080”还是“090”。
【解决方案2】:
使用下标之间的索引,如:
str[0:3] or str [:3]
这会将光标从第 0 个索引移到第 2 个索引