I have been trying to convert an integer into a string. My codes are as follows:
n = 357
x = str(n)
print x
The problem is that online editors that I have tried are not printing the string as '357'. Instead the string is printed as 357. What have I been doing wrong?
You apparently want to print the representation of the string. Python has a builtin function repr(..) for this:
n = 357
x = str(n)
print(repr(x))
The representation of a string is a list of characters between single or double quotes (double quotes if the string contains at least one single quote and no double quotes). Furthermore if there are escape sequences (like a new line), these are printed with a backslash (like \n).
Related
I'm trying to convert binary to decimal to ASCII. Using this code, I'm able to take a binary input and split it into chunks of 7 bits.
def binary_to_ascii7bits(bstring):
n = 7
byte = [bstring[i:i+n] for i in range(0, len(bstring), n)]
print(byte)
I need to be able to turn each 7-bit substring into a decimal number in order to use the chr function. If I try to turn this list into a string, it prints for example, "['1111000']", but I cannot have the brackets and apostrophes in the string. What can I do to fix this?
First of all, for the chr function it should be an integer, not a decimal.
Add this list comprehension before the print function -
byte = [chr(64 + int(i)) for i in byte]
This will give the string for the bytes. I think this is what you want.
You can add just one more line (as below) to achieve what you described.
You have int(..., 2) to convert the string representation of a binary number into an integer. Then apply chr to get a character. This procedure is done using (list) comprehension, so that the result is a list of characters. Then use join to make a single string.
text = '1111000' * 10
def binary_to_ascii7bits(bstring):
n = 7
byte = [bstring[i:i+n] for i in range(0, len(bstring), n)]
return ''.join(chr(int(x, 2)) for x in byte)
print(binary_to_ascii7bits(text)) # xxxxxxxxxx
I am trying this new API that returns numbers. There are four returned. When the function below is called, you'll see four numbers in the terminal but the length of the string is 8. I do not know why. I am trying to manipulate the data to return a horizontal string of four numbers.
import requests
def randomApi():
r = requests.get('https://www.random.org/integers/?num=4&min=0&max=7&col=1&base=10&format=plain&rnd=new')
return ''.join(r.text)
print(randomApi())
print(len(randomApi()))
The API returns a string like '5\n2\n5\n7\n' where the numbers are separated by newlines (represented here by the escape sequence \n). The newline characters contribute to the length of the string, so this string has a length of 8 - four digits plus four newline characters.
To convert them to a "horizontal" string, you can use .replace to convert the newlines to spaces. I suggest using .strip() first to remove the newline at the end of the string, since you probably don't want an extra space at the end of your result.
>>> s = randomApi()
>>> s.strip().replace('\n', ' ')
'3 7 4 7'
I've got a 4 number string corresponding to the code-point of an unicode character.
I need to dynamically convert it to its unicode character to be stored inside a variable.
For example, my program will spit during its loop a variable a = '0590'. (https://www.compart.com/en/unicode/U+0590)
How do I get the variable b = '\u0590'?
I've tried string concatenation '\u' + a but obviously it's not the way.
chr will take a code point as an integer and convert it to the corresponding character. You need to have an integer though, of course.
a = '0590'
result = chr(int(a))
print(result)
On Python 2, the function is called unichr, not chr. And if you want to interpret the string as a hex number, you can pass an explicit radix to int.
a = '0590'
result = unichr(int(a, 16))
print(result)
The part where I need to go from the number values I obtained to characters to spell out a word it not working, it says I need to use an integer for the last part?
accept string
print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))
change it to lower case
string_lowercase=string.lower()
print "lower case string is:", string_lowercase
strip special characters
specialcharacters="1234567890~`!##$%^&*()_-+={[}]|\:;'<,>.?/"
for char in specialcharacters:
string_lowercase=string_lowercase.replace(char,"")
print "With the specials stripped out the string is:", string_lowercase
input offset
offset=(int(raw_input("enter offset:")))
conversion of text to ASCII code
result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
conversion from ASCII code to text
text=''.join(chr(i) for i in result)
print "The decoded string is:", text.format(chr(result))
It looks like you have a list of lists instead of a list of ints when you call result.append([code-offset]). This means later when you call chr(i) for i in result, you are passing a list instead of an int to chr().
Try changing this to result.append(code-offset).
Other small suggestions:
raw_input already gives you a string, so there's no need to explicitly cast it.
Your removal of special characters can be more efficiently written as:
special_characters = '1234567890~`!##$%^&*()_-+={[}]|\:;'<,>.?/'
string_lowercase = ''.join(c for c in string_lowercase if string not in special_characters)
This allows you to only have to iterate through string_lowercase once instead of per character in special_characters.
While doing .append() to list, use code-offset instead of [code-offset]. As in later you are storing the value as a list (of one ASCII) instead of storing the ASCII value directly.
Hence your code should be:
result = []
for i in string_lowercase:
code = ord(i)
result.append(code-offset)
However you may simplified this code as:
result = [ord(ch)-offset for ch in string_lowercase]
You may even further simplify your code. The one line to get decoded string will be:
decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)
Example with offset as 2:
>>> string_lowercase = 'abcdefghijklmnopqrstuvwxyz'
>>> offset = 2
>>> decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)
>>> decoded_string
'_`abcdefghijklmnopqrstuvwx'
You are passing a list to chr when it only accepts integers. Try result.append(code-offset). [code-offset] is a one-item list.
Specifically, instead of:
result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
use:
result=[]
for i in string_lowercase:
code=ord(i)
result.append(code-offset)
If you understand list comprehension, this works too: result = [ord(i)-offset for i in string_lowercase]
I am working on a program that reads an RFID card, and then pulls information about that card from a database. I am using Python with MySQL for this but in order for it to work I need to convert a string, e.g. "2345d566k", to an int. I don't need the letters to be in there, just the numbers.
when I do the following:
test = "2345d566k"
test2 = int(test)
it returns: ValueError: invalid literal for int() with base 10: '2345d566k'
How could I convert this string to an int?
Assuming you want to ignore characters other than digits, a simple solution would be
test = "ab23cd56e3f"
test2 = int(filter(lambda x: x.isdigit(), test))
#test2 is now 23563
filter() applies the isdigit() function to every character of the string, keeping only those that are digits. Then you can safely call int() to convert the result to an integer.
As pointed out in the comments, this will only work if every line of text you want to convert contains at least 1 digit.
You can easily use regex for this
import re
"".join(re.findall('\d', "ab23cd56e3f"))
It will parse all numeric digit from the given string, If you will put \D in place of \d it will result all alphabets.