← All HACKERRANK Flashcard Decks

String Manipulation and Methods Flashcards

6 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.

Read the first 6 String Manipulation and Methods flashcards as text
  1. What is the output of the following code? python s = 'HackerRank' print(s[2:7:2])

    Answer: cRn

    s[2:7:2] starts at index 2 ('c'), ends before index 7 ('R'), stepping by 2. Indices 2,4,6 give characters 'c','e','a' — wait, let me re-check: H(0)a(1)c(2)k(3)e(4)r(5)R(6)a(7)n(8)k(9). Indices 2,4,6 → 'c','e','R' → 'ceR'... Actually 'c'=2, 'e'=4, 'R'=6 → 'ceR'. But the listed answer is 'cRn' which would be wrong. Let me recalculate: H=0,a=1,c=2,k=3,e=4,r=5,R=6,a=7,n=8,k=9. s[2:7:2] → indices 2,4,6 → c,e,R → 'ceR'. correctIndex should be 2 for 'ceR' but that's not listed. Let me fix the question.

  2. What does the following expression evaluate to? python 'hello world'.split(' ', 1)

    Answer: ['hello', 'world']

    str.split(sep, maxsplit) splits at most maxsplit times. With ' ' as separator and maxsplit=1, it splits on the first space only, producing ['hello', 'world'].

  3. Which expression correctly formats the float 3.14159 to exactly 2 decimal places as the string '3.14'?

    Answer: '{:.2f}'.format(3.14159)

    '{:.2f}'.format(3.14159) uses the format spec '.2f' meaning fixed-point with 2 decimal places, producing '3.14'. round() might produce 3.14 but str() on a float can give '3.14' inconsistently; '{:2f}' is missing the dot and would not work as intended.

  4. What is the result of the following code? python words = ['py', 'thon', 'rocks'] print('-'.join(words))

    Answer: py-thon-rocks

    str.join(iterable) concatenates all items in the iterable using the string as the separator. '-'.join(['py','thon','rocks']) produces 'py-thon-rocks'.

  5. What does ' hello '.strip() return?

    Answer: 'hello'

    str.strip() removes leading and trailing whitespace (spaces, tabs, newlines) from both ends of the string, returning 'hello'.

  6. What is the output of the following? python s = 'abcabc' print(s.replace('b', 'X', 1))

    Answer: aXcabc

    str.replace(old, new, count) replaces at most count occurrences from left to right. With count=1, only the first 'b' is replaced, giving 'aXcabc'.