Checking Whether a String Starts with Xxxx

Checking whether a string starts with XXXX

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

More info about startswith.

In python How do i check whether a string starts with special symbol or not?

In a slice, the end index is exclusive. Therefore, self.str[:0] always returns an empty string (it stops just before the zeroth character).

The correct way to write that slice is self.str[:1].

A more idiomatic to perform the check is

self.str.startswith('{')

Finding whether a string starts with one of a list's variable-length prefixes

A bit hard to read, but this works:

name=name[len(filter(name.startswith,prefixes+[''])[0]):]

Efficient method of checking if a string starts with one of a set of strings

With a compiled regular expression, I would expect the overhead of compiling a regex to pay itself back when you have more than just a few strings. Basically, the compiled regex is an automaton which runs out of traversable paths pretty quickly if the prefix is not one which the automaton recognizes. Especially if all the matches are anchored to the beginning of the string, it should fail very quickly when there is no match.

import re

prefixes = ['foo', 'bar', 'baz']
rx = re.compile(''.join(['^(?:', '|'.join(prefixes), ')']))
for line in input:
match = rx.match(line)
if match:
matched = match.group(0)

If you need a more complex regular expression (say, one with trailing context after the closing parenthesis), you will want to use regular grouping parentheses ( instead of non-grouping (?:, and fetch group(1) instead.

Here is the same with a dictionary mapping prefixes to replacements:

prefixes = {'foo': 'nu', 'bar': 'beer', 'baz': 'base'}
rx = re.compile(''.join(['^(?:', '|'.join(prefixes.keys()), ')']))
for line in input:
match = rx.match(line)
if match:
newval = prefixes[match.group(0)]

Actually, as pointed out in comments, the ^ is not strictly necessary with re.match().

Detect what a python string begins with

You're looking for str.startswith

if file_string.startswith("begin_like_this"):

find whether the string starts and ends with the same word

You can use backreference within regex

^(\w+\b)(.*\b\1$|$)

This would match a string only if it

  • starts and ends with the same word
  • has a single word

bash if string starts with character

Try to use bashregex instead, like this:

...
if [[ $i =~ ^et.* ]]; then
echo "$i"
fi
...

Match if string starts with n digits and no more

Use a negative lookahead:

regexp = re.compile(r'^\d{3}(?!\d)')

Python remove sentence if it is at start of string and starts with specific words?

You can use

docs = [re.sub(r'^H(?:ello|i)\b.*?[.?!]\s+', '', doc) for doc in docs]

See the regex demo. Details:

  • ^ - start of string
  • H(?:ello|i)\b - Hello or Hi word (\b is a word boundary)
  • .*? - any zero or more chars other than line break chars as few as possible
  • [.?!] - a ., ? or !
  • \s+ - one or more whitespaces.

See the Python demo:

import re
docs = ['Hi, my name is Eric. Are you blue?',
"Hi, I'm ! What is your name?",
'This is a great idea. I would love to go.',
'Hello, I am Jane Brown. What is your name?',
"Hello, I am a doctor! Let's go to the mall.",
'I am ready to go. Mom says hello.']
docs = [re.sub(r'^H(?:ello|i)\b.*?[.?!]\s+', '', doc) for doc in docs]
print(docs)

Output:

[
'Are you blue?',
'What is your name?',
'This is a great idea. I would love to go.',
'What is your name?',
"Let's go to the mall.",
'I am ready to go. Mom says hello.'
]


Related Topics



Leave a reply



Submit