How can I concatenate and integer with a string? - string

I'm receiving an error when I try to concatenate weight_kg with a string "kilograms". I want the numerical output of weight_kg followed by the string "kilograms". E.g. '50 kilograms'.
I've tried to convert weight_kg as a string so I can concatenate it to the string "kilograms"
weight_lbs = input("Weight (lbs): ")
weight_kg = int(weight_lbs) * 0.45
print(weight_kg)
print(weight_kg) + str("kilograms")
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

print(weight_kg) + str("kilograms")
you were trying to add the return value of a print() (which is a NoneType) to a string. They can't be added together.
You might want something like this:
print( str(weight_kg) + "kilograms" )
which converts weight_kg to string first then concatenates and prints the result out.

Try this:
print(str(weight_kg)+"kilograms")
no need to cast a string again to string,
and use str(object) to case object to str (like integer at your case)
and print function syntax is print("things to be printed <must be inside the () of the print func>")
to concatenate a 2 strings just str3=str_1+str_2
so according to this all :
print(str(weight_kg)+"kilograms")

Related

Trouble concatenating floats and strings in Python

I'm using this code:
for each in x:
descrVar = descrVar + " " + df.iloc[counter,each]
to iterate through a table and concatenate cells into a variable. The problem is, some of the cells will be a Nan. As a result, I'm getting the following error:
TypeError: can only concatenate str (not "numpy.float64") to str
I assume this means a Nan is a float64 and not a str. Is there any way around this, such as forcing every cell to convert to a str?
An f-string will format your data as str.
for each in x:
descrVar += f" {df.iloc[counter,each]}"

Letters in String to Dictionary Values

I am trying to take the letters from the string 'Hello, World!' and convert it into values using a dictionary.
I've tried using strings and lists to see if this would work but can't figure it out.
d ={'H':1, 'e':2, 'l':3, 'o':4,',':5, ' ':6, 'W':7, 'r':8, 'd':9, '!':10}
mystr = 'Hello, World!'
mystr1 = d(mystr)
print(mystr1)
TypeError: 'dict' object is not callable is the error I keep getting.
'Hello, World!'
My expected output is: '12334567483910'
If possible I would also like a way to convert the number back to the words 'Hello, World!'
You can do what you're trying to do by converting your dictionary to a translation table and then using the str.translate method.
d = {'H':'1', 'e':'2', 'l':'3', 'o':'4',',':'5', ' ':'6', 'W':'7', 'r':'8', 'd':'9', '!':'10'}
tt = str.maketrans(d)
print("Hello, World!".translate(tt))
# 12334567483910
Note that we had to change the values of the dictionary from integers to strings, otherwise the str.maketrans method treats them like Unicode ordinals.
You need to iterate on each character of mystr. So using the get method, we can retrieve the value from the dictionary without causing an error if the character isn't there (and just leave it out), for c in mystr loops through each character, and the str function converts the integer from the dictionary to a string (if the values in the dictionary were strings you wouldn't need it, although then you could use translate as in Patrick's answer). Finally, ''.join joins all the characters back together into a new string.
Instead of the get method, if you want it to throw an error if the character is not in the dictionary you can use d[c] instead of d.get(c, '').
d ={'H':1, 'e':2, 'l':3, 'o':4,',':5, ' ':6, 'W':7, 'r':8, 'd':9, '!':10}
mystr = 'Hello, World'
encoded_string = ''.join(str(d.get(c, '')) for c in mystr)
print('Encoded String:', encoded_string)
r = dict((value, key) for key, value in d.items())
decoded_string = ''.join(r.get(int(c)) for c in encoded_string)
print('Decoded String:', decoded_string)
Result
Encoded String: 123345674839
Decoded String: Hello, World

How to convert a string value in dataframe to float

I have a csv file and I have to clean data.The problem is that I can fill the empty values by df.fillna() but there are some continious numbers in string which needs to be converted to float or int for further calculations.
I tried couple of methods but cannot find a solution.
Kindly help as I am new in data science field and maybe have made some mistake asking the question.
This column has an string value : df['hum'][316] = '64.70'
type(df['hum'][316]) = str
I stored the string value to a variable and then used float(value) but it gives an error.
value = df['hum'][316]
>>>' "64.70"'
type(value)
>>> str
float(value)
>>>ValueError: could not convert string to float: ' "64.70"'
ValueError: could not convert string to float: ' "64.70"'
df['hum'][316] = float(df['hum'][316])
seems the problems is the " inside the string, remove it by using a regular expression
import re
value = df['hum'][316]
value=re.sub('"','',value)
float(value)
instead of float possible to check also astype for cast operations applying on the whole df or series (column)
if you want to change the whole column of df to a float try:
df['hum'] = df['hum'].str.replace('"', '')
df['hum']=df['hum'].astype('float')
regards giulio

Replace non-numeric characters in string

I would like to know how to replace non-numeric characters in a single string with different random integers.
I have tried the following:
text = '1$1#387'
rec_1 = re.sub("\D+",str(random.randint(0,9)),text)
It then produced:
output: 1717387
As you can see, the non-numeric characters have been replaced by the same integer. I would like each non-numeric character to be replaced by a different integer. For example:
desired output: 1714387
Please assist.
Use a function as the replacement value:
def replacement(match):
return str(random.randint(0, 9))
text = '1$1#387'
rec_1 = re.sub(r"\D", replacement, text)
rec_1 is now "1011387", or "1511387", ...
That's because the randint function is called only 1 time.
You can use a lambda to get a new randint each time:
rec_1 = re.sub("\D+", lambda x: str(random.randint(0, 9)), text)

MATLAB: Concatenate number value as string

I want to create a binary number in matlab and am having difficulty concatenating the numbers.
Here's what I tried so far:
testarray = zeros(10,10)
testarray = num2str(testarray) % Convert all values to type string
testarray(1,1) = num2str(1); % Fill with abitrary value
testarray(1,1) = strcat(testarray(1,1), num2str(0)); % Trying to make '10' here but instead I get this error: "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
Any help would be appreciated.
In your example, the problem is that '10' has size [1,2], but testarray(1,1) has size [1,1]. So you might consider using cells instead:
testarray = cell(5,5);
testarray{1,1} = strcat(testarray(1,1), num2str(0));
By the way, you should have a look at the function dec2bin.
From the documentation:
dec2bin(23)
ans =
10111
The resulting value is a string.
So if you want to concatenate two binary values (encoded as strings), just do:
['10' '11']
ans =
1011

Resources