i am trying to get the numbers in individual form added to a list.
For example, if i input 3245, i want the list to say
["3","2","4","5"]
I have tried using a for in statement but got back numbers ranging from 0 - 3244 which was expected.
Any insight would be greatly appreciated, i am very new to python and am trying to teach myself code and re-write all my projects for school that was done in c to turn them into python. NOTE: i am using python 3, not 2.
Here is the rest of my code if it helps.
cc = []
card = int(input("Credit Card: "))
for n in range(card):
cc.append(n)
print(cc)
First of all, you should either accept the input number as string or convert it to string. That way, you can just parse through each character in the string and add them to the list. Currently you are getting the number 0-3244 because of you are looping for the amount of inputted number and adding the loop index to your list. Therefore, this should do what you want
cc = []
card = input("Credit Card: ") # or str(int(input("Credit Card: ")))
# if you want to restrict it to integer
for n in range(len(card)): # loop by number of characters
cc.append(card[n]) # append each character
print(cc)
a = 3245
b = list(str(a))
print(b)
The above code can convert an integer to a list of characters. First convert the integer to a string and then convert the string to a list form.
you can just convert the integer to string and iterate through every character of the string and during the iteration just append to cc.
cc = []
card = int(input("Credit Card: "))
for i in str(card):
cc.append(i)
print(cc)
Related
I have used the following code but not getting the desired output. please help me.
"{}{}{}".format((random.choices(string.ascii_uppercase)for i in range(5)), random.randint(1000,9999))
I don't know exactly why it doesn't work, but I managed to get it to print the desired result using this code:
x = []
y = ""
for i in range(5):
x += random.choices(string.ascii_uppercase)
x += str(random.randint(1000,9999))
print (y.join(x))
My guess is that it's because you're trying to add a list (your method of string generation produces a list of string characters) and an integer (randint produces an integer) to a string.
I have a document and it contain numbers in between is there a way I can replace all the numbers to the English equivalent ?
eg:
My age is 10. I am in my 7th grade.
expected-o/p :
My age is Ten and I am in my seventh grade.
Thanks in advance
You'll want to take a look at num2words.
You'll have to construct regexp to catch the numbers you want to replace and pass them to num2words. Based on example provided, you also might need the ordinal flag.
import re
from num2words import num2words
# this is just an example NOT ready to use code
text = "My age is 10. I am in my 7th grade."
to_replace = set(re.findall('\d+', text)) # find numbers to replace
longest = sorted(to_replace, key=len, reverse=True) # sort so longest are replaced first
for m in longest:
n = int(m) # convert from string to number
result = num2words(n) # generate text representation
text = re.sub(m, result, text) # substitute in the text
print(text)
edited to reflect that OP wants to catch all digits
I'm fairly new to Python,
I'm trying to check if the user input can be checked in a range of integers
The following is the code I have already written
#LL DD LLL
#where L is a letter
#where D is a digit
#eg SG 61 ABC
area_codes = ["SG", "PV", "LJ", "EX"]
reg = input("Enter registration: ")
if reg[0:2] in area_codes:
print(reg[0:2])
if reg[2:3] in range(0,18):
print(reg[2:3])
else:
print("nope")
And this is the response I am given,
Enter registration: SG15
SG
nope
How do I check this properly?
I have tried a few things but I don't even know if this is possible.
Thank you in advance,
Donberry.
reg[2:3] is a slice of your input string. So it's a number, but stored as string.
When you do:
if reg[2:3] in range(0,18):
you're checking if the string in contained in the range object (python 3) or list object (python 2) which contains integers. So the test fails every time.
Had you done
if 0 <= reg[2:3] < 18:
you'd have gotten an explicit error in python 3. Besides, it avoids to build a range or list object just for the sake of testing. Chained comparison like this is way faster.
So I'm suggesting:
if 0 <= int(reg[2:3]) < 18:
You should convert the string to an integer before checking it's in the range. Also, (and I don't know if you did this), but you should verify that you want numbers between 0 and 17, which is what your code does.
That is, range(0, 18) - equivalent to range(18), by the way - generates the list of numbers starting at 0 and ending at 17, including both 0 and 17.
Anyway, you would check it like this:
if int(reg[2:3]) in range(0,18):
print(reg[2:3])
I'm using python 3.x. I'm trying to get the (int) number at the end of a string with format
string_example_1 = l-45-98-567-567-12
string_example_2 = s-89-657
or in general, a single lowercase letter followed by a number of integers separated by '-'. What I need is to get the last number (12 and 657 in these cases). I have archived this with the function
def ending(the_string):
out = ''
while the_string[-1].isdigit():
out = the_string[-1] + out
the_string = the_string[:-1]
return out
but I'm sure there must be a more pythonic way to do this. In a previous instance I check manually that the string starts the way I like by doing something like
if st[0].isalpha() and st[1]=='-' and st[2].isdigit():
statement...
I would just split the string on -, take the last of the splits and convert it to an integer.
string_example_1 = "l-45-98-567-567-12"
string_example_2 = "s-89-657"
def last_number(s):
return int(s.split("-")[-1])
print(last_number(string_example_1))
# 12
print(last_number(string_example_2))
# 657
Without regular expressions, you could reverse the string, take elements from the string while they're still numbers, and then reverse the result. In Python:
from itertools import takewhile
def extract_final_digits(s):
return int(''.join(reversed(list(takewhile(lambda c: c.isdigit(), reversed(s))))))
But the simplest is to just split on a delimiter and take the final element in the split list.
I am trying to write an RSA code in python3. I need to turn user input strings (containing any characters, not only numbers) into integers to then encrypt them. What is the best way to turn a sting into an integer in Python 3.6 without 3-rd party modules?
how to encode a string to an integer is far from unique... there are many ways! this is one of them:
strg = 'user input'
i = int.from_bytes(strg.encode('utf-8'), byteorder='big')
the conversion in the other direction then is:
s = int.to_bytes(i, length=len(strg), byteorder='big').decode('utf-8')
and yes, you need to know the length of the resulting string before converting back. if length is too large, the string will be padded with chr(0) from the left (with byteorder='big'); if length is too small, int.to_bytes will raise an OverflowError: int too big to convert.
The #hiro protagonist's answer requires to know the length of the string. So I tried to find another solution and good answers here: Python3 convert Unicode String to int representation. I just summary here my favourite solutions:
def str2num(string):
return int(binascii.hexlify(string.encode("utf-8")), 16)
def num2str(number):
return binascii.unhexlify(format(number, "x").encode("utf-8")).decode("utf-8")
def numfy(s, max_code=0x110000):
# 0x110000 is max value of unicode character
number = 0
for e in [ord(c) for c in s]:
number = (number * max_code) + e
return number
def denumfy(number, max_code=0x110000):
l = []
while number != 0:
l.append(chr(number % max_code))
number = number // max_code
return ''.join(reversed(l))
Intersting: testing some cases shows me that
str2num(s) = numfy(s, max_code=256) if ord(s[i]) < 128
and
str2num(s) = int.from_bytes(s.encode('utf-8'), byteorder='big') (#hiro protagonist's answer)