Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a string starts with XXXX

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?

like image 679
John Marston Avatar asked Jan 10 '12 11:01

John Marston


People also ask

How do you check if a string starts with a string?

Definition and Usage. The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false .

How do you check if a string starts with a specific letter?

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.

How do you check if a string starts with Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

How do you check if a string starts with a word in Python?

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.


2 Answers

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

More info about startswith.

like image 127
RanRag Avatar answered Oct 13 '22 22:10

RanRag


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.

like image 35
Shawabawa Avatar answered Oct 13 '22 22:10

Shawabawa