I would like to know how to check whether a string starts with "hello" in Python.
In Bash I usually do:
if [[ "$string" =~ ^hello ]]; then do something here fi
How do I achieve the same in Python?
Definition and Usage. The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false .
We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.
The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .
The startswith() string method checks whether a string starts with a particular substring. If the string starts with a specified substring, the startswith() method returns True; otherwise, the function returns False.
aString = "hello world" aString.startswith("hello")
More info about startswith
.
RanRag has already answered it for your specific question.
However, more generally, what you are doing with
if [[ "$string" =~ ^hello ]]
is a regex match. To do the same in Python, you would do:
import re if re.match(r'^hello', somestring): # do stuff
Obviously, in this case, somestring.startswith('hello')
is better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With