Home > Back-end >  Is there a function that makes python read only some parts of a string and execute an operation
Is there a function that makes python read only some parts of a string and execute an operation

Time:12-05

I'm trying to make my Python read only the first 3 digits of a string and print an answer based on the first three digits of the string.

I tried:

if str[1,2,3] = 080:
   print(...)
elif str[123] =090:
   print(,,,)

CodePudding user response:

Here is how you can achieve this in 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")

In this code, we use the string[:3] syntax to get the first three characters of the string. Then, we use if and elif statements to check if the first three characters are "080" or "090".

CodePudding user response:

use the index between the subscript like:

str[0:3] or str [:3]

this will take the cursor from 0th index to 2nd index

  • Related