I tried to convert int into hex and concatenate the hex into a string and write it to files.
but when i do the following:
c = ""
c = hex(a) + hex(b)
i got error saying
'str' object cannot be interpreted as an integer.
How to solve this in python3.5?
Solved:
it turns out a is a string and i want to strip off the leading 0x so a better way that transforms this to plain hex is to do {0:02x}.format(yourHex).
a and b should be integer because hex takes integer and it returns string so you can concatenate the output of those two hex().
a = 5
b = 7
c = ""
filePath = "C:\\..\\..\\hexFile.txt" #Path of your file
with open(filePath, "w") as file:
c = hex(a) + hex(b)
file.writelines(c)
Related
So basically my homework consists of making a program that asks for a string and an integer 'x'.'x' is basically the step in this program. First it converts the whole string to lowercase and then each 'x'th' character of the string must be converted to uppercase. So if i input "Hello World" and my integer is 1. Output would be "hElLo wOrLd". Im new to python by the way.
This is what ive got right now and im basically stuck in a loop of trying a 100 things:
s = input('Input a string: ')
g = input('Input an integer: ')
s = s.lower() #converts the whole string ofc
s = list(s)
range1 = s[::g]
range1 = range1.upper()
print(s)
First, convert g to an int because input returns a str and you can't slice a list with a str, also, s[::g] (which should be s[g::g + 1]) is an independent sublist of s, and it has no reference to s, so assigning it to range1 and modifying it will not modify s, and one more note, s[::g] is a list, and you should call str.upper on its elements, not on it itself, you can use map for this:
s = list(input('Input a string: ').lower())
g = int(input('Input an integer: '))
s[g::g + 1] = map(str.upper, s[g::g + 1])
s = ''.join(s)
print(s)
Input:
Input a string: Hello World
Input an integer: 1
Output:
hElLo wOrLd
having a brain fart. But how do i decode a string that contains.
t = '%2Fdata%2F'
print(t.decode('utf8'))
'str' object has no attribute 'decode'
expecting /data/
2F is a hexadecimal number of / character. Python has chr function that returns a character representation by a decimal number.
So you need to get two symbols after %s and "decode" ("hex" -> chr(int("hex",16))) them into a character.
def decode_utf(string):
for i in range(string.count("%")):
tmp_index = string.index("%")
hex_chr = string[tmp_index:tmp_index + 3]
#replace only one characher at a time
string = string.replace(hex_chr, chr(int(hex_chr[1:],16)),1)
return string
print(decode_utf("%2Fdata%2F"))
#/data/
print(decode_utf("hello%20world%21"))
#hello world!
Edit 1:
The previous code breaks if there's %25 character, use the code below.
def decode_utf(string):
utf_characters = []
tmp_index = 0
for i in range(string.count("%")):
tmp_index = string.index("%",tmp_index)
hex_chr = string[tmp_index:tmp_index + 3]
if not hex_chr in utf_characters:
utf_characters.append(hex_chr)
tmp_index += 1
for hex_chr in utf_characters:
string = string.replace(hex_chr, chr(int(hex_chr[1:],16)))
return string
print(decode_utf("%25t%20e%21s%2ft%25"))
#%t e!s/t%
I want to write a code in MATLAB that converts a letter into NATO alphabet. Such as the word 'hello' would be re-written as Hotel-Echo-Lima-Lima-Oscar. I have been having some trouble with the code. So far I have the following:
function natoText = textToNato(plaintext)
plaintext = lower(plaintext);
r = zeros(1, length(plaintext))
%Define my NATO alphabet
natalph = ["Alpha","Bravo","Charlie","Delta","Echo","Foxtrot","Golf", ...
"Hotel","India","Juliet","Kilo","Lima","Mike","November","Oscar", ...
"Papa","Quebec","Romeo","Sierra","Tango","Uniform","Victor",...
"Whiskey","Xray","Yankee","Zulu"];
%Define the normal lower alphabet
noralpha = ['a' : 'z'];
%Now we need to make a loop for matlab to check for each letter
for i = 1:length(text)
for j = 1:26
n = r(i) == natalph(j);
if noralpha(j) == text(i) : n
else r(i) = r(i)
natoText = ''
end
end
end
for v = 1:length(plaintext)
natoText = natoText + r(v) + ''
natoText = natoText(:,-1)
end
end
I know the above code is a mess and I am a bit in doubt what really I have been doing. Is there anyone who knows a better way of doing this? Can I modify the above code so that it works?
It is because now when I run the code, I am getting an empty plot, which I don't know why because I have not asked for a plot in any lines.
You can actually do your conversion in one line. Given your string array natalph:
plaintext = 'hello'; % Your input; could also be "hello"
natoText = strjoin(natalph(char(lower(plaintext))-96), '-');
And the result:
natoText =
string
"Hotel-Echo-Lima-Lima-Oscar"
This uses a trick that character arrays can be treated as numeric arrays of their ASCII equivalent values. The code char(lower(plaintext))-96 converts plaintext to lowercase, then to a character array (if it isn't already) and implicitly converts it to a numeric vector of ASCII values by subtracting 96. Since 'a' is equal to 97, this creates an index vector containing the values 1 ('a') through 26 ('z'). This is used to index the string array natalph, and these are then joined together with hyphens.
When I have a matrix, which has values written like 5.34000E+5. When I try to create a string variable, with the following value mat(1,1), which contains the 5.340000E+5, Matlab creates a string variable with 534000. How can I create a string variable like 5.34000E+5?
Thanks
You need to specify the formatting while converting:
>> number = 534000
number = 534000
>> s = num2str(number,'%10.5e\n')
s =
5.34000e+05
>> class(s)
ans = char
You can use sprintf
num = 534000;
str = sprintf('%.0f',num);
str2 = sprintf('%e',num);
disp(str);
disp(str2);
Here, % means that you want to specify format, f means float and .0 means that you want no decimals e means that you want it as exponential. For more info on this see sprintf format specifiers.
I have a character string array in Fortran as ' results: CI- Energies --- th= 89 ph=120'. How do I extract the characters '120' from the string and store into a real variable?
The string is written in the file 'input.DAT'. I have written the Fortran code as:
implicit real*8(a-h,o-z)
character(39) line
open(1,file='input.DAT',status='old')
read(1,'(A)') line,phi
write(*,'(A)') line
write(*,*)phi
end
Upon execution it shows:
At line 5 of file string.f (unit = 1, file = 'input.dat')
Fortran runtime error: End of file
I have given '39' as the dimension of the character array as there are 39 characters including 'spaces' in the string upto '120'.
Assuming that the real number you want to read appears after the last equal sign in the string, you can use the SCAN intrinsic function to find that location and then READ the number from the rest of the string, as shown in the following program.
program xreadnum
implicit none
integer :: ipos
integer, parameter :: nlen = 100
character (len=nlen) :: str
real :: xx
str = "results: CI- Energies --- th= 89 ph=120"
ipos = scan(str, "=", back=.true.)
print*, "reading real variable from '" // trim(str(1+ipos:)) // "'"
read (str(1+ipos:),*) xx
print*, "xx = ", xx
end program xreadnum
! gfortran output:
! reading real variable from '120'
! xx = 120.000000
To convert string s into a real type variable r:
READ(s, "(Fw.d)") r
Here w is the total field width and d is the number of digits after the decimal point. If there is no decimal point in the input string, values of w and d might affect the result, e.g.
s = '120'
READ(s, "(F3.0)") r ! r <-- 120.0
READ(s, "(F3.1)") r ! r <-- 12.0
Answer to another part of the question (how to extract substring with particular number to convert) strongly depends on the format of the input strings, e.g. if all the strings are formed by fixed-width fields, it's possible to skip irrelevant part of the string:
s = 'a=120'
READ(s(3:), "(F3.0)") r