String to Int in Python 3
String in Python:
Python strings are characters enclosed in single, double, or triple quotes. The computer does not understand the characters, which internally stores altered characters as strings of 0s and 1s.
The ASCII or Unicode char is used to encode each character. Thus, we can also refer to Python strings as Unicode characters.
Python allows you to create strings by enclosing a character or string of characters in quotes. Python allows us to create this same string using single, double, or triple quotes.
string = "Hi everyone!"
print(string)
OUTPUT:
Hi everyone!
Here, if we use a Python script to determine the type of variable str.
str = "This is a string!"
print(str)
print(type(str))
OUTPUT:
This is a string!
<class 'str'>
Python does not support this same character data type because strings have been treated as sequences of characters; instead, only one character written as "p" is treated as a string of length 1.
Creating a String:
Although it is typically used for multiline strings or docstrings, Python also
Offers triple quotes to depict the string. We can turn them into a string by enclosing the same characters in single or double quotes.
CODE:
#creating a string using single quotes
string1 = 'Hello everyone'
print(string1)
#creating a string using double quotes
string2 = "This is a string"
print(string2)
#creating a string using triple quotes
string3 = ''''' Typically, multiline or document
strings are enclosed in triple quotes.'''
print(string3)
OUTPUT:
Hello everyone
This is a string
''Typically, multiline or document
strings are enclosed in triple quotes.
String Indexing and Slicing:
The Python string indexing begins at 0, just like other languages. For instance, the index for the string "ROHIT" is displayed below.
CODE:
string = "JAMES"
print(string[0])
print(string[1])
print(string[2])
print(string[3])
print(string[4])
# The absence of the sixth index causes it to return an index error.
print(string[6])
OUTPUT:
J
A
M
E
S
IndexError Traceback (most recent call last)
Input In [14], in <cell line: 8>()
6 print(string[4])
7 # It returns the IndexError because 6th index doesn't exist
----> 8 print(string[6])
IndexError: string index out of range
Accessing a string's characters in Python uses the slice operator []. But in Python, we can access this same substring from the supplied string using the: (colon) operator.
The example below should be considered.
CODE:
string = "GEORGE IS A STUDENT"
print(string[0:9])
print(string[1:5])
print(string[0:])
print(string[:])
""" if you give a number which is over an extend(range),
It prints the entire string and doesn’t give an error."""
print(string[:2100])
OUTPUT:
GEORGE IS
EORG
GEORGE IS A STUDENT
GEORGE IS A STUDENT
GEORGE IS A STUDENT
The rightmost character in the string, denoted as -1, is where we can begin
the negative slicing operation. The next to the rightmost index reads "-2," and so forth. Think about the information below.
string = "GEORGE IS A STUDENT"
print(string[0:-4])
# -1 represents the last element in the string
print(string[-1])
print(string[7:-1])
OUTPUT:
GEORGE IS A STU
T
IS A STUDEN
Assigning it to a new string makes updating the content of strings simple. Since a string's content could be partially replaced, the string object does not support item assignment, so a string may only be replaced with a new string. Python supports immutable strings.
s = "HEY"
s[0] = "Y"
print(s)
OUTPUT:
TypeError Traceback (most recent call last)
Input In [44], in <cell line: 2>()
1 s = "HEY"
----> 2 s[0] = "Y"
3 print(s)
TypeError: 'str' object does not support item assignment.
str = "THIS IS STRING1"
print(str)
str = "this is string2"
print(str)
OUTPUT:
THIS IS STRING1
this is string2
Python Int():
To obtain an integer value, use Python's int() function. It gives back an expression that has been transformed into an integer value. The number is converted to a long type if the assertion is outside the integer range. The conversion halts the number if the assertion is a Floating point value.
The number must be a string if it isn't a number or a base is specified.
In Python, an integer is a whole number with zero, a positive or a negative sign, and unlimited precision, such as 0, 100, or -10. In Python, the following literals for integers are acceptable. Binary, octal, and hexadecimal values can all be used as integers. The int class comprises all integer literals and variables.
x=0b11011000 # It is a binary number
y=0o12 # It is octal
z=0x12 # It is hexadecimal
print(x)
print(y)
print(z)
OUTPUT:
216
10
18
# Declaring the variables
value1 = 10 #this is an integer
value2 = 10.52 # val2 holds floating value
value3 = '10' # value3 holds the string.
# Checking values of their types
print(type(value1), type(value2), type(value3))
# Calling int() function
value4 = int(value1)
value5 = int(value2)
value6 = int(value3)
# Displaying the Output
print("values after conversion ",value4, value5, value6)
print("and types are: \n ", type(value4), type(value5), type(value6))
OUTPUT:
<class 'int'> <class 'float'> <class 'str'>
values after conversion 10 10 10
and types are:
<class 'int'> <class 'int'> <class 'int'>
Python’s built-in int() feature can translate strings into integers. The int() function transforms any Scripting language data type into an integer. However, doing so is not limited to using the int() function. The float () can also perform this conversion since float values can be used to compute integers. Here is a list of potential Python methods for converting an integer to a string:
number = int(input("Enter a number:"))
# checking and printing a type number variable
print(type(number))
# converting the number into a string
converted_number = int(number)
# printing type of converted_number
print(type(converted_number))
# We can check it by doing some mathematical/statistical operations
print("After converting:")
print(converted_number + 10)
OUTPUT:
number = int(input("Enter a number:"))
# checking and printing a type number variable
print(type(number))
# converting the number into a string
converted_number = int(number)
# printing type of converted_number
print(type(converted_number))
# We can check it by doing some mathematical/statistical operations
print("After converting:")
print(converted_number + 10)
str='Learning Python is fun'
a= 20
#Displaying the type of a and b
print(type(str1))
print(type(a))
OUTPUT:
<class 'str'>
<class 'int'>
The variables "a" and "b" were declared in the example above with a string and an integer value, respectively.
We can use type to confirm their data types (). The obvious question is why it is necessary to transform a string into an integer.
a = "100"
b = "26"
result = a * b
print("The multiplication/product of a and b gives: ",res)
OUTPUT:
TypeError Traceback (most recent call last)
Input In [65], in <cell line: 3>()
1 a = "100"
2 b = "26"
----> 3 result = a * b
4 print("The multiplication/product of a and b gives: ",res)
TypeError: can't multiply sequence by non-int of type 'str.'
We must convert this same input, i.e., string value, to integers to easily continue the operations because it causes this kind of error.
Now let's look at the program that shows how to convert a string to an integer
a_value= '7'
print(type(a_value))
#using int()
conv_a_value=int(a_value)
print(type(conv_a_value))
conv_a_value = conv_a_value+10
print(conv_a_value)
print(type(conv_a_value))
OUTPUT:
<class 'str'>
<class 'int'>
17
<class 'int'>
CODE EXPLANATION:
- The variable "a" must first be declared and given a string value.
- After that, we used type to determine its data type ().
- We used the int() function to convert a string to an integer, verifying the type.
- The variable "a" has now been changed by appending 10.
- The output displays the outcome value at the end.
We'll use an indirect method to change a string into an integer.
a_value = input("Enter a value:")
b_value = input("Enter b value:")
print(type(a_value))
print(type(b_value))
#converting it to float
a_value=float(a_value)
#converting it to int
b_value=int(b_value)
result=a_value+b_value
print("The sum of value_a and value_b is ",result)
OUTPUT:
Enter a value:1.2
Enter b value:43
<class 'str'>
<class 'str'>
The sum of value_a and value_b is 44.2
CODE EXPLANATION:
- The first step is to declare the two variables "value a" and "value b" with a given string.
- Following that, we used type to determine their data type ().
- We used float() to transform the string to a float value to convert it to an integer.
- We will change the “value b” string into an integer in the following step.
- Value a and Value b have now been added, and their sum has been printed.
- The output displays the outcome value at the end.
We'll examine how to change a number represented as a given string on a different base to a base 10 number.
a_value = '234'
# printing a value.
print('The value of a is :', a_value)
#assuming that 234 is in base 10 and converting it to base 10
print('The value of a from base 10 to base 10 is:', int(a_value))
#assuming that 234 is in base 8 and converting it to base 10
print('The value of a from base 8 to base 10 is :', int(a_value, base=8))
#assuming that 234 is in base 6 and converting it to base 10
print('The value of a base 6 to base 10 is :', int(a_value, base=6))
OUTPUT:
The value of a is: 234
The value of a from base 10 to base 10 is: 234
The value of a from base 8 to base 10 is: 156
The value of a base 6 to base 10 is: 94