How to Change Any Data Type into a String

Pandas: change data type of Series to String

A new answer to reflect the most current practices: as of now (v1.2.4), neither astype('str') nor astype(str) work.

As per the documentation, a Series can be converted to the string datatype in the following ways:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

Convert any array of any type into string

Write a utility method like below:

public static String convertToString(Object input){
if (input instanceof Object[]) {
// deepToString used to handle nested arrays.
return Arrays.deepToString((Object[]) input);
} else {
return input.toString();
}
}

Please note that the first if condition would be evaluated to false if the input is a primitive array like int[], boolean[], etc. But it would work for Integer[] etc.
If you want the method to work for primitive arrays, then you need to add conditions for each type separately like:

else if (input instanceof int[]){
// primitive arrays cannot be nested.
// hence Arrays.deepToString is not required.
return Arrays.toString((Object[]) input);
}

How to convert instance of any type to string?

I'm not sure you even need a function, but this would be the shortest way:

function( arg ) {
return arg + '';
}

Otherwise this is the shortest way:

arg += '';

Converting a custom type to string in Go

Convert the value to a string:

func SomeFunction() string {
return string(Foobar)
}

Convert to a datatype given in string format

You have to map the strings to a type. Since not all of them are System.<yourType> directly, I would consider creating a mapping:

Dictionary<string, Type> types = new Dictionary<string, Type>();
types.Add("int", typeof(System.Int32);
//etc.

Then, use Convert.ChangeType to get your object:

object myObj = Convert.ChangeType(b, types[a]);

Maybe you could extend this by trying to get the type if the key does not exist in your type mapping:

object myObj = Convert.ChangeType(b, Type.GetType("System." + a));


Related Topics



Leave a reply



Submit