aString = "hello world"
aString.startswith("hello")
More info about startswith.
Videos
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.
str.startswith can take a tuple of strings as an argument. It will return true if the string starts with any of them.
s.startswith(('http://', 'https://'))
However, it might be simpler to use a regular expression to capture the idea of the s being optional:
bool(re.match('https?://', s))
If the match succeeds, you get back a truthy re.Match object. If the match fails, you get back the falsy value None.
you can use urllib.parse.urlparse
from urllib.parse import urlparse
url = 'https://www.youtube.com/watch?v=nVNG8jjZN7k'
if urlparse(url).scheme in ("http", "https"):
...
More useful methods in the docs https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse
If you want to match non-ASCII letters as well, you can use str.isalpha:
if line and line[0].isalpha():
You can pass a tuple to startswiths() (in Python 2.5+) to match any of its elements:
import string
ALPHA = string.ascii_letters
if line.startswith(tuple(ALPHA)):
pass
Of course, for this simple case, a regex test or the in operator would be more readable.
If the values to check are all 1 character (or all the same length) you could use the in operator with a substring to get the first letter(s):
if variable[:1] in ("a", "e", "i", "o", "u"):
...
or
if variable[:1] in "aeiou":
...
You can write a function that checks if the string provided starts with a vowel:
def starts_with_vowel(str):
return str.lower().startswith(("a", "e", "i", "o", "u")) # lower to be more general
variable1 = "open"
# check if it starts with a vowel
if starts_with_vowel(variable1):
print("correct")
str.startswith allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])Return
Trueif string starts with theprefix, otherwise returnFalse.prefixcan also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
You can also use any(), map() like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something