What is the most Python way to check if a string starts with a particular string?

Asked 2 years ago, Updated 2 years ago, 105 views

When I try to figure out if the string starts with "hello," I usually use a slicer I wonder if there is an easier way than this.

mystring = "hello python world!"

if mystring[:len("hello")] == "hello":
    print("yes!")

string string-comparison

2022-09-22 22:12

1 Answers

This feature is already implemented as a Python standard function. You can use str.startswith() for example

string = "hello world"
string.startswith("hello")


2022-09-22 22:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.