Hackerrank String Manipulation and Methods — Questions and Answers
Question 1: What is the output of the following code? python s = 'HackerRank' print(s[2:7:2])
- cRn (Correct answer)
- ckea
- cke
- ckR
Correct 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.
Question 2: What does the following expression evaluate to? python 'hello world'.split(' ', 1)
- ['hello', 'world'] (Correct answer)
- ['hello world']
- ['h', 'ello world']
- ['hello', ' ', 'world']
Correct 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'].
Question 3: Which expression correctly formats the float 3.14159 to exactly 2 decimal places as the string '3.14'?
- '{:.2f}'.format(3.14159) (Correct answer)
- str(round(3.14159, 2))
- '{:2f}'.format(3.14159)
- format(3.14159, '2d')
Correct 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.
Question 4: What is the result of the following code? python words = ['py', 'thon', 'rocks'] print('-'.join(words))
- py-thon-rocks (Correct answer)
- ['py', 'thon', 'rocks']
- py thon rocks
- pythonn-rocks
Correct 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'.
Question 5: What does ' hello '.strip() return?
- 'hello' (Correct answer)
- ' hello '
- 'hello '
- ' hello'
Correct answer: 'hello'
str.strip() removes leading and trailing whitespace (spaces, tabs, newlines) from both ends of the string, returning 'hello'.
Question 6: What is the output of the following? python s = 'abcabc' print(s.replace('b', 'X', 1))
- aXcabc (Correct answer)
- aXcaXc
- abcaXc
- aXXabc
Correct 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'.
What is the output of the following code?
python
s = 'HackerRank'
print(s[2:7:2])