String search in Python

Posted under » Python on 13 March 2009

You can assign a multiline string to a variable by using three quotes

a = """LK Y is
a cool dude in Hell."""

b = '''Goh C cant
wait to join LK Y.'''

To get the length of a string, use the len() function

a = "Hello World!"
print(len(a))

Strings in Python are arrays of bytes representing unicode characters.

a = "Hello World!"
print(a[1])

To check if a certain phrase or character is present in a string, we can use the keyword in.

txt = "Hello World"
if "Hell" in txt:
  print("Yes, 'Hell' is present.")

The good thing about `in' is that it is not case sensitive. So hello and Hello will be found.

Check if "cool" is NOT present in the following text:

txt = "Hello World"
if "cool" not in txt:
  print("No, 'cool' is NOT present.")

If you want to check the number (count) of `l' in "Hello World",

txt = "Hello World"
counter = txt.count('l')

3

See also Python String into array

It is a bit different from string search in PHP.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data