Python - String Methods,Python Booleans, Python Operators

 

String Methods

Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Joins the elements of an iterable to the end of the string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning

Test Yourself With Exercises

Now you have learned a lot about Strings, and how to use them in Python.

Are you ready for a test?

Try to insert the missing part to make the code work as expected:

Test Yourself With Exercises

Exercise:

Use the len method to print the length of the string.

x = "Hello World"
print()

Go to the Exercise section and test all of our Python Strings Exercises:

Python String Exercises

Booleans represent one of two values: True or False.


Boolean Values

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

Example

print(10 > 9)
print(10 == 9)
print(10 < 9)
Try it Yourself »

When you run a condition in an if statement, Python returns True or False:

Example

Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")
Try it Yourself »

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return,

Example

Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))
Try it Yourself »

Example

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))
Try it Yourself »


Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

Example

The following will return True:

bool("abc")
bool(123)
bool(["apple""cherry""banana"])
Try it Yourself »

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as ()[]{}"", the number 0, and the value None. And of course the value False evaluates to False.

Example

The following will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Try it Yourself »

One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False:

Example

class myclass():
  def __len__(self):
    return 0

myobj = myclass()
print(bool(myobj))
Try it Yourself »

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

Example

Print the answer of a function:

def myFunction() :
  return True

print(myFunction())
Try it Yourself »

You can execute code based on the Boolean answer of a function:

Example

Print "YES!" if the function returns True, otherwise print "NO!":

def myFunction() :
  return True

if myFunction():
  print("YES!")
else:
  print("NO!")
Try it Yourself »

Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:

Example

Check if an object is an integer or not:

x = 200
print(isinstance(x, int))
Try it Yourself »

Python Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

print(10 + 5)
Run example »

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

OperatorNameExampleTry it
+Additionx + yTry it »
-Subtractionx - yTry it »
*Multiplicationx * yTry it »
/Divisionx / yTry it »
%Modulusx % yTry it »
**Exponentiationx ** yTry it »
//Floor divisionx // yTry it »

Python Assignment Operators

Assignment operators are used to assign values to variables:

OperatorExampleSame AsTry it
=x = 5x = 5Try it »
+=x += 3x = x + 3Try it »
-=x -= 3x = x - 3Try it »
*=x *= 3x = x * 3Try it »
/=x /= 3x = x / 3Try it »
%=x %= 3x = x % 3Try it »
//=x //= 3x = x // 3Try it »
**=x **= 3x = x ** 3Try it »
&=x &= 3x = x & 3Try it »
|=x |= 3x = x | 3Try it »
^=x ^= 3x = x ^ 3Try it »
>>=x >>= 3x = x >> 3Try it »
<<=x <<= 3x = x << 3Try it »


Python Comparison Operators

Comparison operators are used to compare two values:

OperatorNameExampleTry it
==Equalx == yTry it »
!=Not equalx != yTry it »
>Greater thanx > yTry it »
<Less thanx < yTry it »
>=Greater than or equal tox >= yTry it »
<=Less than or equal tox <= yTry it »

Python Logical Operators

Logical operators are used to combine conditional statements:

OperatorDescriptionExampleTry it
and Returns True if both statements are truex < 5 and  x < 10Try it »
orReturns True if one of the statements is truex < 5 or x < 4Try it »
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)Try it »

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

OperatorDescriptionExampleTry it
is Returns True if both variables are the same objectx is yTry it »
is notReturns True if both variables are not the same objectx is not yTry it »

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

OperatorDescriptionExampleTry it
in Returns True if a sequence with the specified value is present in the objectx in yTry it »
not inReturns True if a sequence with the specified value is not present in the objectx not in yTry it »

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

OperatorNameDescription
ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
 ^XORSets each bit to 1 if only one of two bits is 1
NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Post a Comment

0 Comments