Bird
Raised Fist0
NumPydata~20 mins

String type in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NumPy String Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this NumPy string array creation?
Consider the following code that creates a NumPy array of strings. What will be the output?
NumPy
import numpy as np
arr = np.array(['cat', 'dog', 'bird'], dtype='S4')
print(arr)
A[b'cat' b'dog' b'bird']
Bb'cat' b'dog' b'bird'
C]'drib'b 'god'b 'tac'b[
D[b'cat' b'dog' b'bir']
Attempts:
2 left
💡 Hint
Remember that dtype='S4' means each string is stored with 4 bytes, truncating longer strings.
❓ data_output
intermediate
2:00remaining
What is the length of each element in this NumPy string array?
Given this NumPy array of strings, what is the length of each element stored internally?
NumPy
import numpy as np
arr = np.array(['apple', 'banana', 'cherry'], dtype='S6')
lengths = np.char.str_len(arr)
print(lengths)
A[5 6 6]
B[5 6 6 ]
C[5 6 6 7]
D]6 6 5[
Attempts:
2 left
💡 Hint
Check how dtype='S6' affects string storage and length calculation.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error when assigning a longer string?
Look at this code snippet. Why does it raise an error or truncate the string when assigning a longer string to a NumPy string array element?
NumPy
import numpy as np
arr = np.array(['cat', 'dog'], dtype='S3')
arr[0] = 'elephant'
print(arr)
AIt raises a ValueError because 'elephant' is longer than 3 bytes allowed by dtype='S3'.
BIt converts 'elephant' to bytes and stores fully without truncation.
CIt raises a TypeError because strings cannot be assigned to NumPy arrays.
DIt truncates 'elephant' to 'ele' silently without error.
Attempts:
2 left
💡 Hint
Consider how fixed-length string dtypes handle longer strings assigned to elements.
❓ visualization
advanced
2:00remaining
Visualize the difference between Unicode and byte string arrays in NumPy
Which option shows the correct plot comparing the memory size of Unicode (U) and byte (S) string arrays of length 5 with 1000 elements?
NumPy
import numpy as np
import matplotlib.pyplot as plt
arr_s = np.array(['abcde']*1000, dtype='S5')
arr_u = np.array(['abcde']*1000, dtype='U5')
sizes = [arr_s.nbytes, arr_u.nbytes]
labels = ['S5', 'U5']
plt.bar(labels, sizes)
plt.ylabel('Memory size in bytes')
plt.title('Memory size: byte vs Unicode strings')
plt.show()
ABar chart with 'S5' bar larger than 'U5' bar
BPie chart showing 'S5' and 'U5' equal parts
CBar chart with 'S5' bar smaller than 'U5' bar
DLine chart showing sizes equal
Attempts:
2 left
💡 Hint
Unicode strings use more bytes per character than byte strings.
🧠 Conceptual
expert
2:00remaining
Which statement about NumPy string dtypes is TRUE?
Select the correct statement about fixed-length string dtypes in NumPy.
ANumPy Unicode string dtype 'U' stores each character as 1 byte, same as byte strings 'S'.
BNumPy byte string dtype 'S' stores strings as fixed-length bytes and truncates longer strings silently.
CAssigning a longer string than the dtype length to a NumPy string array element raises a runtime error.
DNumPy string arrays automatically resize to fit longer strings assigned to elements.
Attempts:
2 left
💡 Hint
Think about how fixed-length string arrays handle storage and assignment.

Practice

(1/5)
1. Which NumPy string type should you use to store Unicode text like emojis or accented characters?
easy
A. Use 'U' type for Unicode strings.
B. Use 'S' type for Unicode strings.
C. Use 'i' type for Unicode strings.
D. Use 'f' type for Unicode strings.

Solution

  1. Step 1: Understand NumPy string types

    NumPy has two main string types: 'S' for byte strings (ASCII) and 'U' for Unicode strings.
  2. Step 2: Identify correct type for Unicode

    Unicode strings require 'U' type to support characters beyond ASCII, like emojis or accented letters.
  3. Final Answer:

    Use 'U' type for Unicode strings. -> Option A
  4. Quick Check:

    Unicode text = 'U' type [OK]
Hint: Unicode needs 'U', ASCII uses 'S' type [OK]
Common Mistakes:
  • Using 'S' type for Unicode causes data loss
  • Confusing numeric types with string types
  • Assuming 'U' is for byte strings
2. Which of the following is the correct way to create a NumPy array of byte strings with length 5?
easy
A. np.array(['hello', 'world'], dtype='int5')
B. np.array(['hello', 'world'], dtype='U5')
C. np.array(['hello', 'world'], dtype='S5')
D. np.array(['hello', 'world'], dtype='float5')

Solution

  1. Step 1: Identify byte string dtype syntax

    Byte strings use dtype='S' followed by the fixed length, e.g., 'S5' for length 5.
  2. Step 2: Check options for correct dtype

    np.array(['hello', 'world'], dtype='S5') uses 'S5', which is correct for byte strings of length 5.
  3. Final Answer:

    np.array(['hello', 'world'], dtype='S5') -> Option C
  4. Quick Check:

    Byte strings = 'S' + length [OK]
Hint: Byte strings use dtype='S' plus length number [OK]
Common Mistakes:
  • Using 'U' instead of 'S' for byte strings
  • Using invalid dtypes like 'int5' or 'float5'
  • Omitting the length number after 'S'
3. What will be the output of this code?
import numpy as np
arr = np.array(['cat', 'dog', 'elephant'], dtype='S5')
print(arr)
medium
A. ['cat' 'dog' 'eleph']
B. [b'cat' b'dog' b'eleph']
C. [b'cat' b'dog' b'elephant']
D. ['cat' 'dog' 'elephant']

Solution

  1. Step 1: Understand dtype='S5' effect

    Using dtype='S5' means fixed-length byte strings of length 5, so strings longer than 5 characters get truncated.
  2. Step 2: Check each string length and truncation

    'cat' and 'dog' fit within 5 bytes, but 'elephant' is longer and gets truncated to 'eleph'.
  3. Final Answer:

    [b'cat' b'dog' b'eleph'] -> Option B
  4. Quick Check:

    Fixed length 5 truncates 'elephant' to 'eleph' [OK]
Hint: Fixed-length strings truncate longer text [OK]
Common Mistakes:
  • Expecting full 'elephant' without truncation
  • Confusing byte strings with Unicode strings
  • Ignoring the 'b' prefix for byte strings
4. The following code throws an error. What is the main issue?
import numpy as np
arr = np.array(['a', 'b', 'c'], dtype='U2')
arr[0] = 'abc'
medium
A. The array must be created with dtype='S3' to assign 'abc'.
B. You cannot assign strings to NumPy arrays.
C. dtype='U2' only supports byte strings, not Unicode.
D. The string 'abc' is longer than dtype='U2' allows.

Solution

  1. Step 1: Understand dtype='U2' limitation

    dtype='U2' means Unicode strings of fixed length 2 characters only.
  2. Step 2: Check assigned string length

    Trying to assign 'abc' (3 characters) to an element that only allows 2 characters causes truncation or error.
  3. Final Answer:

    The string 'abc' is longer than dtype='U2' allows. -> Option D
  4. Quick Check:

    Fixed-length Unicode strings truncate or error on longer input [OK]
Hint: Check string length vs dtype length before assignment [OK]
Common Mistakes:
  • Thinking dtype='U2' supports any length string
  • Believing NumPy arrays can't hold strings
  • Confusing byte strings ('S') with Unicode ('U')
5. You have a list of mixed-length Unicode strings: ['hi', 'hello', 'hey', 'hola']. You want to create a NumPy array that stores all strings without truncation. Which dtype should you choose?
hard
A. dtype='U5' because the longest string has 5 characters.
B. dtype='S5' because it supports Unicode strings up to length 5.
C. dtype='U4' because it is the default for Unicode strings.
D. dtype='S10' to allow extra space for all strings.

Solution

  1. Step 1: Find the longest string length

    The longest string is 'hello' with 5 characters.
  2. Step 2: Choose dtype to fit longest string

    Use dtype='U5' to store Unicode strings up to length 5 without truncation.
  3. Step 3: Avoid byte string dtype for Unicode

    Using 'S' type stores byte strings, not Unicode, so it may cause data loss.
  4. Final Answer:

    dtype='U5' because the longest string has 5 characters. -> Option A
  5. Quick Check:

    Unicode max length = dtype='U' + max length [OK]
Hint: Match dtype length to longest Unicode string [OK]
Common Mistakes:
  • Using 'S' dtype for Unicode strings
  • Choosing dtype length smaller than longest string
  • Assuming default dtype fits all strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard