Working with Numbers & Strings in Python

codewithkenn

CodeWithKenn

Posted on January 17, 2022

Working with Numbers & Strings in Python

Python is one of the most popular coding languages available and is great as a starting point in your learning journey. It can be used for a range of things, such as web and internet development, software development application, network programming, and 3D graphics... (hethelinnovation.com)

*While learning, we end up getting stuck in small bugs that can take more time to solve, whereas we could have solved it quickly if we could only remember the basics. *

So, this is a series of Basics Python tips to remember whenever we work with numbers and strings. You can also use this article as a reference somehow while coding...

Enjoy!

Python Numbers

There are three numeric types we use in Python:

  • int: or integer, is a whole number without decimals.
x = 1245
y = -789

print(type(x))
print(type(y))

Enter fullscreen mode Exit fullscreen mode
  • float: or Floating, a number with one or more decimals.
x = 12.45
y = 42E5

print(type(x))
print(type(y))

Enter fullscreen mode Exit fullscreen mode
  • complex: as studied in high school, is a number written with a "j" as the imaginary part.
x = 3 + 2j
y = -15j

print(type(x))
print(type(y))

Enter fullscreen mode Exit fullscreen mode

Numbers Types Conversion

To convert numbers from one type (from the three) to another, we used methods.

In Python, a method is a function that is available for a given object because of the object's type.
So, You can convert from one type to another with the int(), float(), and complex() methods:


x = 4    # int number
y = 0.8  # float number
z = 4j   # complex number

# from int to float:
a = float(x)

# from float to int:
b = int(y)

# from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Enter fullscreen mode Exit fullscreen mode

Let's Build a Simple Calculator

# Python Simple calculator

# Addition Function
def add(x, y):
    return x + y

# Substraction Function
def subtract(x, y):
    return x - y

# Multiplication Function
def multiply(x, y):
    return x * y

# Division Function
def divide(x, y):
    return x / y


def calculate(first_number, second_number, operator):
    if operator == "+":
        answer = add(first_number, second_number)
        return answer

    elif operator == "-":
        answer = subtract(first_number, second_number)
        return answer

    elif operator == "/":
        answer = divide(first_number, second_number)
        return answer
    elif operator == "*" or operator == "x":
        answer = subtract(first_number, second_number)
        return answer
    else:
        return "Invalid"


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
operator = input("Enter the Operator: ")

print(f"{num1} {operator} {num2} = {calculate(num1, num2, operator)}")

Enter fullscreen mode Exit fullscreen mode

Python Strings

Strings in python are surrounded by:

  • Single quotation marks
'bonjour'
Enter fullscreen mode Exit fullscreen mode
  • Double quotation marks
"bonjour"
Enter fullscreen mode Exit fullscreen mode

Use a Variable to save the String

The assignment sign is made of = (equal sign).

name = "Kennedy"
role = "Software Engineer"
print(name)
print(role)
Enter fullscreen mode Exit fullscreen mode

We can also use Multiline Strings

poem = """Your face is the grave of your nose
your face is the grave of your ears
your face is the grave of your face
once again your face overflows uncontrollably."""

print(poem)
Enter fullscreen mode Exit fullscreen mode

Accessing a Character of the String

We can think of strings like an array made of characters. For example, the word "Elon Musk" is made of "E", "l", "o", "n", " ", "M", "u", "s" and "k" (Notice the space is also counted as a character).

The first character is counted at index 0 (not 1).

greeting = "Hello, World!"
print(greeting[1]) #prints "e" 
Enter fullscreen mode Exit fullscreen mode

Working with Strings

Checking the String Length

use the len() function

name = "Kennedy"
length_of_name = len(name)

print(length_of_name)
Enter fullscreen mode Exit fullscreen mode

Checking an existing string or character in a string

Use the in keyword.

sentence = "Kennedy is a python programmer"
if "python" in a sentence:
  print("Yes, 'python' is present.")
Enter fullscreen mode Exit fullscreen mode

Most Common String Methods

  • capitalize() method converts the first character of a string to an uppercase letter and lowercases all other characters.
name = "python"
print(name.capitalize())
Enter fullscreen mode Exit fullscreen mode
  • casefold() method Converts string into lower case.
name = "PYTHON"
print(name.casefold())
Enter fullscreen mode Exit fullscreen mode
  • upper() method converts all the characters into Uppercase.
name = "python"
print(name.upper())
Enter fullscreen mode Exit fullscreen mode
  • lower() method converts all the characters into Lowercase.
name = "PYTHON"
print(name.lower())
Enter fullscreen mode Exit fullscreen mode
  • len() method used to count the total number of characters in a string.
name = "python"
print( len(name) )
Enter fullscreen mode Exit fullscreen mode
  • find() searches the string for a specified value and returns the position of where it was found.
sentence = "python is great"
print( sentence.find('great') )
Enter fullscreen mode Exit fullscreen mode
  • replace() is used to replace a string with another.
sentence = "python is great"
new_sentence = sentence.replace('great', 'awesome') 
print(new_sentence)
Enter fullscreen mode Exit fullscreen mode
  • str() is used for string conversion
ten = str(10)
print(ten) #converts 10 to '10'
Enter fullscreen mode Exit fullscreen mode

Let's work on a Small Project

- Arrange string characters such that lowercase letters should come first

Initial Code
noun = PrOgRamMinG
# Expected Output : rgaminPORMG

Solution

noun = "PrOgRamMinG"

def arrange_string(my_string):
    print('Original String:', my_string)
    lower = []
    upper = []

    #Let's iterate and convert
    for char in my_string:
        if char.islower():
            # add lowercase characters to lower list
            lower.append(char)
        else:
            # add uppercase characters to lower list
            upper.append(char)

    # Join both list
    sorted_str = ''.join(lower + upper)
    print('Result:', sorted_str)

# Now, let's call execute the function we just created! 
arrange_string(noun)

# Output: 
# Original String: PrOgRamMinG
# Result: rgaminPORMG
Enter fullscreen mode Exit fullscreen mode

Resources for more Details:

👉 DISCOVER MORE useful ARTICLES

Thanks for reading this article, many others are coming very soon, Feel free to subscribe 🤙.

🌎 Let's connect

Want to start blogging? 🔥Join NOW!

💖 💪 🙅 🚩
codewithkenn
CodeWithKenn

Posted on January 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related