# NumPy: String Exercises, Practice, Solution

## NumPy String [22 exercises with solution]

[An editor is available at the bottom of the page to write and execute the scripts.]

1. Write a NumPy program to concatenate element-wise two arrays of string. Go to the editor
Expected Output:
Array1:
['Python' 'PHP']
Array2:
[' Java' ' C++']
new array:
['Python Java' 'PHP C++']
Click me to see the sample solution

2. Write a NumPy program to repeat all the elements three times of a given array of string Go to the editor
Expected Output:
Original Array:
['Python' 'PHP' 'Java' 'C++']
New array:
['PythonPythonPython' 'PHPPHPPHP' 'JavaJavaJava' 'C++C++C++']
Click me to see the sample solution

3. Write a NumPy program to capitalize the first letter, lowercase, uppercase, swapcase, title-case of all the elements of a given array. Go to the editor
Expected Output:
Original Array:
['python' 'PHP' 'java' 'C++']
Capitalized: ['Python' 'Php' 'Java' 'C++']
Lowered: ['python' 'php' 'java' 'c++']
Uppered: ['PYTHON' 'PHP' 'JAVA' 'C++']
Swapcased: ['PYTHON' 'php' 'JAVA' 'c++']
Titlecased: ['Python' 'Php' 'Java' 'C++']
Click me to see the sample solution

4. Write a NumPy program to make the length of each element 15 of a given array and the string centered / left-justified / right-justified with paddings of _. Go to the editor
Original Array:
['python exercises' 'PHP' 'java' 'C++']
Centered = ['python exercise' '______PHP______' '______java_____' '______C++______'] Left = ['python exercise' 'PHP____________' 'java___________' 'C++____________'] Right = ['python exercise' '____________PHP' '___________java' '____________C++']
Click me to see the sample solution

5. Write a NumPy program to insert a space between characters of all the elements of a given array. Go to the editor
Note: First array elements raised to powers from second array
Expected Output:
Original Array:
['python exercises' 'PHP' 'java' 'C++']
['p y t h o n e x e r c i s e s' 'P H P' 'j a v a' 'C + +']
Click me to see the sample solution

6. Write a NumPy program to encode all the elements of a given array in cp500 and decode it again. Go to the editor
Sample Output:
encoded = [b'\x97\xa8\xa3\x88\x96\[email protected]\x85\xa7\x85\x99\x83\x89\xa2\x85\xa2'
b'\xd7\xc8\xd7' b'\x91\x81\xa5\x81' b'\xc3NN']
decoded = ['python exercises' 'PHP' 'java' 'C++']
Click me to see the sample solution

7. Write a NumPy program to remove the leading and trailing whitespaces of all the elements of a given array. Go to the editor
Sample output:
Original array:
[ -10.2 122.2 0.2]
Element-wise absolute value:
[ 10.2 122.2 0.2]
Click me to see the sample solution

8. Write a NumPy program to remove the leading whitespaces of all the elements of a given array. Go to the editor
Sample Output:
Original Array:
[' python exercises ' ' PHP ' ' java ' ' C++']
Remove the leading whitespaces : ['python exercises ' 'PHP ' 'java ' 'C++']
Click me to see the sample solution

9. Write a NumPy program to remove the trailing whitespaces of all the elements of a given array. Go to the editor
Sample Output:
Original Array:
[' python exercises ' ' PHP ' ' java ' ' C++']
Remove the trailing whitespaces : [' python exercises' ' PHP' ' java' ' C++']
Click me to see the sample solution

10. Write a NumPy program to split the element of a given array with spaces. Go to the editor
Sample Output:
Original Array:
['Python PHP Java C++']
Split the element of the said array with spaces:
[list(['Python', 'PHP', 'Java', 'C++'])]
Click me to see the sample solution

11. Write a NumPy program to split the element of a given array to multiple lines. Go to the editor
Sample output:
Original Array:
['Python\\Exercises, Practice, Solution']
[list(['Python\\Exercises, Practice, Solution'])]
Click me to see the sample solution

12. Write a NumPy program to make all the elements of a given string to a numeric string of 5 digits with zeros on its left. Go to the editor
Sample output:
Original Array:
['2' '11' '234' '1234' '12345']
Numeric string of 5 digits with zeros:
['00002' '00011' '00234' '01234' '12345']
Click me to see the sample solution

13. Write a NumPy program to replace "PHP" with "Python" in the element of a given array. Go to the editor
Sample Output:
Original Array:
['PHP Exercises, Practice, Solution']
New array:
['Python Exercises, Practice, Solution']
Click me to see the sample solution

14. Write a NumPy program to test equal, not equal, greater equal, greater and less test of all the elements of two given arrays. Go to the editor
Expected Output:
Array1:
['Hello' 'PHP' 'JS' 'examples' 'html']
Array2:
['Hello' 'php' 'Java' 'examples' 'html']
Equal test:
[ True False False True True]
Not equal test:
[False True True False False]
Less equal test:
[ True True True True True]
Greater equal test:
[ True False False True True]
Less test:
[False True True False False]
Click me to see the sample solution

15. Write a NumPy program to count the number of "P" in a given array, element-wise. Go to the editor
Sample Output:
Original Array:
['Python' 'PHP' 'JS' 'examples' 'html']
Number of 'P':
[1 2 0 0 0]
Click me to see the sample solution

16. Write a NumPy program to count the lowest index of "P" in a given array, element-wise. Go to the editor
Original Array:
['Python' 'PHP' 'JS' 'EXAMPLES' 'HTML']
count the lowest index of 'P':
[ 0 0 -1 4 -1]
Click me to see the sample solution

17. Write a NumPy program to check whether each element of a given array is composed of digits only, lower case letters only and upper case letters only. Go to the editor
Sample output:
Original Array:
['Python' 'PHP' 'JS' 'Examples' 'html5' '5']
Digits only = [False False False False False True]
Lower cases only = [False False False False True False]
Upper cases only = [False True True False False False]
Click me to see the sample solution

18. Write a NumPy program to check whether each element of a given array starts with "P". Go to the editor
Sample output:
Original Array:
['Python' 'PHP' 'JS' 'examples' 'html']
Test if each element of the said array starts with 'P':
[ True True False False False]
Click me to see the sample solution

19. Write a NumPy program to add two zeros to the beginning of each element of a given array of string values. Go to the editor
Sample output:
Original array:
['1.12' '2.23' '3.71' '4.23' '5.11']
Add two zeros to the beginning of each element of the said array:
['001.12' '002.23' '003.71' '004.23' '005.11']
Alternate method:
['001.12' '002.23' '003.71' '004.23' '005.11']
Click me to see the sample solution

20. Write a NumPy program to replace a specific character with another in a given array of string values. Go to the editor
Sample output:
Original array of string values:
[['Python-NumPy-Exercises']
['-Python-']]
Replace '-' with '=' character in the said array of string values:
[['Python==NumPy==Exercises']
['==Python==']]
Replace '-' with ' ' character in the said array of string values:
[['Python NumPy Exercises']
['Python']]
Click me to see the sample solution

21. Write a NumPy program to count a given word in each row of a given array of string values. Go to the editor
Sample output:
Original array of string values:
[['Python' 'NumPy' 'Exercises']
['Python' 'Pandas' 'Exercises']
['Python' 'Machine learning' 'Python']]
Count 'Python' row wise in the above array of string values:
[[1 0 0]
[1 0 0]
[1 0 1]]
Click me to see the sample solution

22. Write a NumPy program to split a given text into lines and split the single line into array values. Go to the editor
Sample output:
Original text:
01 V Debby Pramod
02 V Artemiy Ellie
03 V Baptist Kamal
04 V Lavanya Davide
05 V Fulton Antwan
06 V Euanthe Sandeep
07 V Endzela Sanda
08 V Victoire Waman
09 V Briar Nur
10 V Rose Lykos
Array from the said text:
[['01' 'V' 'Debby Pramod']
['02' 'V' 'Artemiy Ellie']
['03' 'V' 'Baptist Kamal']
['04' 'V' 'Lavanya Davide']
['05' 'V' 'Fulton Antwan']
['06' 'V' 'Euanthe Sandeep']
['07' 'V' 'Endzela Sanda']
['08' 'V' 'Victoire Waman']
['09' 'V' 'Briar Nur']
['10' 'V' 'Rose Lykos']]
Click me to see the sample solution

Python-Numpy Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Find the index of an item in a list?

Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?

```>>> ["foo", "bar", "baz"].index("bar")
1
```

Caveats follow

Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it:

```list.index(x[, start[, end]])
```

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million:

```>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
```

Only returns the index of the first match to its argument

A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

```>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
```

Most places where I once would have used index, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for index, take a look at these excellent Python features.

Throws if element not present in list

A call to index results in a ValueError if the item's not present.

```>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
```

If the item might not be present in the list, you should either

• Check for it first with item in my_list (clean, readable approach), or
• Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)

Ref: https://bit.ly/2ALwXwe