I have run into an issue where i can't format a string to be printed.
The function is suppossed to convert Binary into Text which is does brilliantly but the printed out result is formatted all the way the right and not the left.
I have tried resolving this by looking up how to format the string but im getting no luck. Im hoping someone can resolve this issue for me.
Heres the code:
elif Converter_Choice2 == str(3):
def Bin_to_Txt():
print("\nYour Message in Binary:")
bin_input = input("")
binary_int = int(bin_input, 2)
byte_number = binary_int.bit_length() + 7 // 8
binary_array = binary_int.to_bytes(byte_number, "big")
ascii_text = binary_array.decode()
clear()
print("\nYour Message in Text:")
print(ascii_text)
Bin_to_Txt()
I tried different ways to format it but im still new to Python 3. I tried putting "ascii_text" into another string to format it, so i could print that string but it didn't work.
ascii_text_formatted = ("{:<15}".format(ascii_text))
print(ascii_text_formatted)
Some advice for this would be great.
Heres a quick Binary code that can be used: 0100100001100101011011000110110001101111
The decoded version should say "Hello".
I managed to find the answer. If anyone else has this issue or something similar try this:
The issue was the variable "binary_array" was printing out invisible numbers before the printed answer in this case "Hello". Due to this it would print "Hello" all the way to the right as the invisible numbers where in front of it.
To fix this issue i added [34:] at the end of the "binary_array" string to remove those invisible numbers from the print. By adding [34:] it means the first 34 characters/numbers wont be printed even if they are invisible. So this can be any number that you need it to be. For example if i changed 34 to 35 it would remove the "H" from "Hello" and print "ello".
Heres some screenshots of the function block and printed responces from before and after adding [34:].
https://imgur.com/a/W25G1FZ
Related
I am using python3 right now. I got a string over here.
How do i print the -57 which is the 5th number counting from right('-' means no valid value)and print it.
I have tried the many ways but don't work for me.
Thank you guys.
525,03,4A5E31F,32,1850,3,5,5,A85E,-87,-8,-57,13,255,80,-
print(text[-5]) will this work?
Split the sting after each ',' and print the 5th to last element.
my_str = '525,03,4A5E31F,32,1850,3,5,5,A85E,-87,-8,-57,13,255,80,-'
print(my_str.split(',')[-5])
Hello guys for example;
def right_justify( in_str):
print("+" * 5,in_str.rjust(11),"+"*5)
right_justify("Hello")
my function prints out;
and why prints out like this?
+++++ Hello +++++
and ı wannt to print this;
+++++Hello+++++
How can ı make this to make it look more beautiful? :)
This is literally what your code outputs:
('+++++', ' Hello', '+++++')
And that's because of the call to rjust(11) which does exactly what the name implies - it justifies the string 11 characters to the right. Remove that method and your output will be exactly what you want it to be.
Use fstring or str.format
Ex:
def right_justify( in_str):
val = "+"*5
print("{}{}{}".format(val, in_str, val))
print(f"{val}{in_str}{val}")
right_justify("Hello")
Output:
+++++Hello+++++
+++++Hello+++++
I have several files in a folder named t_000.png, t_001.png, t_002.png and so on.
I have made a for-loop to import them using string formatting. But when I use the for-loop I got the error
No such file or directory: '/file/t_0.png'
This is the code that I have used I think I should use multiple %s but I do not understand how.
for i in range(file.shape[0]):
im = Image.open(dir + 't_%s.png' % str(i))
file[i] = im
You need to pad the string with leading zeroes. With the type of formatting you're currently using, this should work:
im = Image.open(dir + 't_%03d.png' % i)
where the format string %03s means "this should have length 3 characters and empty space should be padded by leading zeroes".
You can also use python's other (more recent) string formatting syntax, which is somewhat more succinct:
im = Image.open(f"{dir}t_{i:03d}")
You are not padding the number with zeros, thus you get t_0.png instead of t_000.png.
The recommended way of doing this in Python 3 is via the str.format function:
for i in range(file.shape[0]):
im = Image.open(dir + 't_{:03d}.png'.format(i))
file[i] = im
You can see more examples in the documentation.
Formatted string literals are also an option if you are using Python 3.6 or a more recent version, see Green Cloak Guy's answer for that.
Try this:
import os
for i in range(file.shape[0]):
im = Image.open(os.path.join(dir, f't_{i:03d}.png'))
file[i] = im
(change: f't_{i:03d}.png' to 't_{:03d}.png'.format(i) or 't_%03d.png' % i for versions of Python prior to 3.6).
The trick was to specify a certain number of leading zeros, take a look at the official docs for more info.
Also, you should replace 'dir + file' with the more robust os.path.join(dir, file), which would work regardless of dir ending with a directory separator (i.e. '/' for your platform) or not.
Note also that both dir and file are reserved names in Python and you may want to rename your variables.
Also check that if file is a NumPy array, file[i] = im may not be working.
I am trying to do something that should be very simple. I am a bit frustrated for why my code won't work, so any help is appreciated :).
My program reads in data, and then makes a dictionary that records the number of times a particular item occurs (I am using Twitter data and counting hashtag occurrences). I want to output the top tweets, and have found a nice easy way to do that using the following:
def main():
tweet_file = open(sys.argv[1])
tweet_dic = lines(tweet_file) #function that makes my dictionary
for i in range(0,10):
big_key = max(tweet_dic, key = lambda i: tweet_dic[i])
big_value = tweet_dic[big_key]
sys.stdout = big_key + " " + str(big_value)
del tweet_dic["big_key"]
tweet_file.close()
The error I get on using this is AttributeError: 'str' object has no attribute 'write'
Now I have outputted the two different values into terminal using print just fine, they can be put in two different print statements with no problems since I don't have to concatenate or anything. I have checked the two variables types, and as expected they are always str & int.
My understanding of the str(integer to convert) function is that you should be able to pass in an integer and get a string representation back! After it has been converted, I have been able to print out things like this in the past with no issues.
Things to consider that may be throwing it out - the big_key can sometimes be a string that was converted from Unicode by .encode('utf-8'). Otherwise the output from my file (printing on separate lines) looks like:
MTVHottest 60
KCAMexico 38
EXO 26
CD9 24
Unicode 19
Coders 18
AlonsoVillapandoTrendy 17
Unicode 14
Unicode 14
Any ideas? Thanks in advance!
The error you're getting is because of this: https://docs.python.org/2/library/sys.html#sys.stdout
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
stdout and stderr are the locations where the data is written, you aren't supposed to assign data itself to stdout, which is what it looks like you're doing.
As others have mentioned you would assign stdout to where you want and then use the print command to actually get the data to go there. But if all you're trying to do is print a line of text to a file then why not just open the file and write to it normally?
with open(tweet_file, 'w') as f:
f.write(big_key + " " + str(big_value))
The specific error you're getting is from the line:
sys.stdout = big_key + " " + str(big_value)
This is not how things are output to stdout.
Using a print would be the appropriate way to do that:
print(big_key + " " + str(big_value))
There are some other strange things in your code example, like for example using big_key and then "big_key" in quotes. So probably that's not the end of your bugs and errors.
I try to use google polyline to decode the data. My data looks like
'yrwFpjpbMbDxB|BxAtBxAjFhDrFnDFHlBnAtBtAzBvAvFrDl#\\MfFNHo#~CtF|BXLn#aDp#}Cp#mCfAuD\{AlKmg##]L{#pAoGNup#bCoL#gBf#eC^gBb#cBjD{P\oBVyAFgA?cAs#_QK}#Q_AYcAa#cA]i#m#w#w#q#a#WuCyAcAk#}#o#aA{#}#}#aBuBG[m#m#oEuFcAwAmB}CeDaG_FcJqAeCm#oAKe#Yu#c#aBa#cB[eBEa#fCeBlCYzGq#ZzG'
If I put this string into the code
polyline.decode('yrwFpjpbMbDxB|BxAtBxAjFhDrFnDFHlBnAtBtAzBvAvFrDl#\\MfFNHo#~CtF|BXLn#aDp#}Cp#mCfAuD\{AlKmg##]L{#pAoGNup#bCoL#gBf#eC^gBb#cBjD{P\oBVyAFgA?cAs#_QK}#Q_AYcAa#cA]i#m#w#w#q#a#WuCyAcAk#}#o#aA{#}#}#aBuBG[m#m#oEuFcAwAmB}CeDaG_FcJqAeCm#oAKe#Yu#c#aBa#cB[eBEa#fCeBlCYzGq#ZzG'), it gives me the data.
However, if I run the program and save the string into a list, like code[],
and run the code
polyline.decode(code[0]), the error will say:
IndexError: string index out of range
I tried many times and cannot figure the problem.Can anybody tell me what I'm doing wrong? Thanks in advance!
It might be related to the escape characters in your string.
I a similar issue when copy/pasting a an encoded string from a web call into a python script as a raw string:
encoded_string = r"<pasted string>"
l = polyline.decode(encoded_string)
>>
>> .. IndexError: string index out of range
When making it a normal string (removing the 'r' qulification) it worked
encoded_string = "<pasted string>"
l = polyline.decode(encoded_string)