Making a string out of a string and an integer in Python
name = 'b' + str(num)
or
name = 'b%s' % num
Note that the second approach is deprecated in 3.x.
How to get integer values from a string in Python?
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
If there are multiple integers in the string:
>>> map(int, re.findall(r'\d+', string1))
[498]
Concatenating string and integer in Python
Modern string formatting:
"{} and {}".format("string", 1)
Python strings and integer concatenation
NOTE:
The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str()
function instead.
You can use:
string = 'string'
for i in range(11):
string +=`i`
print string
It will print string012345678910
.
To get string0, string1 ..... string10
you can use this as YOU suggested:
>>> string = "string"
>>> [string+`i` for i in range(11)]
For Python 3
You can use:
string = 'string'
for i in range(11):
string += str(i)
print string
It will print string012345678910
.
To get string0, string1 ..... string10
, you can use this as YOU suggested:
>>> string = "string"
>>> [string+str(i) for i in range(11)]
converting string to integer in Python
instead of ascii value, your are appending a list to ASCII
First, we map each string character to ASCII value and convert it into a string type. Then join with the join function.
e = 100
n = 20
text = input("string >>>")
#This will return int ascii values for each character. Here you can do any arithmatic operations
rsa_values = list(map(lambda x:(ord(x)**e) % n , text))#[16, 1, 5, 16]
#TO get the same you can list compression also
rsa_values = [ (ord(x)**e) % n for x in text] #[16, 1, 5, 16]
#if you need to join them as string then use join function.
string_ascii_values = "".join(chr(i) for i in ascii_values)#'\x10\x01\x05\x10'
Update
Based on Copperfield's commentA better way to do following arithmetic operation
(ord(x)**e) % n
is
pow(ord(x), e, n)
rsa_values = [ pow(ord(x), e, n) for x in text] #[16, 1, 5, 16]
converting Integer to String process (under the hood)
String to integer
Let's start with converting a string to an int, as I think it's a bit simpler to think through. I'll make a few assumptions to start:
- our int method will only deal with int inputs, no floats, complex numbers, etc. for now.
- we will only deal with positive numbers for now as well.
- I won't be dealing with intentionally wrong inputs, like int("Wassup")
The implementation will go through the string input from right to left, and build up the integer number by number.
def custom_int(input):
# Your intuition is right that we will need some kind of look up! this matches a character to a number
s_to_i_dict= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
# imagine our input is the string "123", we want to build up the number 123
# one digit at a time. If you break it down, 123 is equal to 100 + 20 + 3
# Thinking it through further, that's the same as 1*100 + 2*10 + 3*1
# So for each digit going right to left, we'll multiply it by some multiplier
# add it to our result, theb change that multiplier to handle the next digit.
multiplier = 1
output = 0
# This is a little shortcut to get you looping through a list or a string from the last element to the first:
for digit in input[::-1]:
# digit is a character, we find the corresponding number, multiply it by the multiplier, then add it to the old version of output
output = output + ( s_to_i_dict[digit] * multiplier)
# we are done with this digit, so the next multiplier should be 10 times the last (going from digits to tens to hundreds etc.)
multiplier = multiplier * 10
return output
Running this you'd get:
s_to_i("123")
123
type(s_to_i("123"))
<class 'int'>
For the "123" input, our loop will run 3 times. the first time around output will just be the rightmost digit 3, the next time around, we will add 2*10 to output, giving us 23.
The final time through the loop we will get 23 + 1*100, or 123.
Integer to string
We can apply the exact same pattern to the int to string conversion. The same assumptions apply as I won't cover all edge cases, but fundamentally we will do the same thing: go through the numbers from right to left, then build up a string representation of the number.
Now we can't loop over numbers as easily as we loop over strings, but with some good use of mod and division we can get a similar pattern. say n = 123, how do we get just the rightmost digit from the number? Well the rightmost digit is the remainder of dividing n by 10, or in code rightmost_digit = n % 10.
Once we have the rightmost digit, the next step is to try to extract the second rightmost digit, 2 in this case. There are a few ways to do that but my favorite is to recognize that we have already grabbed the rightmost digit, so we don't need it anymore
We can update our number n as follows: n = n // 10
which will give n the value of 12 instead of 123. This is called integer division, and is basically primary school division before you discovered floats :P
How does this help? well notice that 2 is the rightmost digit of 12 and we already know how to grab that! Let's put this all together in a function.
def i_to_s(input):
# Notice that this is the opposite dictionary than before. ints are the key, and they give us the character we need.
i_to_s_dict={0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
# This time we want our output to be a string so we initialize an empty string
output = ""
# There are more precise ways to set up this loop, as this one creates an edge case I'll leave up to you to find, but works with _almost_ every integer :P
while(input != 0):
rightmost_digit = input % 10
# We concatenate the new character we found with the output we've accumulated so far
output = i_to_s(rightmost_digit) + output
# Change the initial number for the next iteration
input = input // 10
return output
i_to_s(123)
'123'
type(i_to_s(123))
<class 'str'>
How to extract numbers from a string in Python?
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
Why can't Python print an integer and string together without converting it?
written by Programiz
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion.
- Implicit Type Conversion
- Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
When we run the above program, the output will be:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
In the above program,
We add two variables num_int and num_flo, storing the value in num_new.
We will look at the data type of all three objects respectively.
In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
Also, we can see the num_new has a float data type because Python always converts smaller data types to larger data types to avoid the loss of data.Now, let's try adding a string and an integer, and see how Python deals with it.
Example 2: Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the above program,
We add two variables num_int and num_str.
As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions.
However, Python has a solution for these types of situations which is known as Explicit Conversion.Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.
Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
In the above program,
We add num_str and num_int variable.
We converted num_str from string(higher) to integer(lower) type using int() function to perform the addition.
After converting num_str to an integer value, Python is able to add these two variables.
We got the num_sum value and data type to be an integer.
How to convert string to integer without using library functions in Python?
The "purest" I can think of:
>>> a = "546"
>>> result = 0
>>> for digit in a:
result *= 10
for d in '0123456789':
result += digit > d
>>> result
546
Or using @Ajax1234's dictionary idea if that's allowed:
>>> a = "546"
>>> value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
>>> result = 0
>>> for digit in a:
result = 10 * result + value[digit]
>>> result
546
How do I parse a string to a float or int?
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Related Topics
Name This Python/Ruby Language Construct (Using Array Values to Satisfy Function Parameters)
Numpy Selecting Specific Column Index Per Row by Using a List of Indexes
How to Make a Cross-Module Variable
Priority of the Logical Operators Not, And, or in Python
Str' Object Does Not Support Item Assignment
Sharing a Result Queue Among Several Processes
How to Create a Reference to a Variable in Python
Why Is a List Comprehension So Much Faster Than Appending to a List
Show Default Value for Editing on Python Input Possible
How to Prevent Numbers Being Changed to Exponential Form in Python Matplotlib Figure
Combine Two Pandas Data Frames (Join on a Common Column)
Sort List of Lists Ascending and Then Descending
Negative Integer Division Surprising Result
Python Ctypes - Loading Dll Throws Oserror: [Winerror 193] %1 Is Not a Valid Win32 Application
In Matplotlib, What Does the Argument Mean in Fig.Add_Subplot(111)