w3resource

Create and print TensorFlow string tensor in Python

Python TensorFlow Basic: Exercise-16 with Solution

Write a Python program that creates a TensorFlow tensor with a string data type and print its value.

Sample Solution:

Python Code:

import tensorflow as tf

# Create a TensorFlow tensor with a string data type
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
string_tensor = tf.constant("TensorFlow Exercises!", dtype=tf.string)

# Print the value of the string tensor
print("String Tensor Value:", string_tensor.numpy().decode())

Output:

String Tensor Value: TensorFlow Exercises!

Explanation:

In the exercise above -

  • Import TensorFlow as tf.
  • Create a TensorFlow tensor "string_tensor" containing the string "TensorFlow Exercises!" with the specified data type tf.string.
  • To print the value of the string tensor, we use .numpy().decode() to convert the tensor to a Python string and then decode it.

Go to:


PREV : Convert TensorFlow Tensor data type in Python.
NEXT : TensorFlow building and training a simple model Exercises Home.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.