1. Home
2. Docs
3. Exercises
4. String Exercises

# String Exercises

## String Exercises.

In this you will find String Exercises, try these exercises on your own.

and then check out the solutions. There are multiple ways to solve a problem,

below solutions are the easy ones. These may not be the best solution.

The purpose of these exercises is to, make you understand the usage of Python language.

str1 = “this is a sample DaTaa”

Exercise 1: Check if ‘is’ present in str1

Solution:

```if 'is' in str1:

print("'is' is substring of ", "'" + str1 + "'")

```

Exercise 2: Check if ‘was’ not present in str1

Solution:

```if 'was' not in str1:

print("'was' is not a substring of ", "'" + str1 + "'")

```

Exercise 3: Print str1 in uppercase

Solution:

```print(str1.upper())

```

Exercise 4: Print str1 in lowercase

Solution:

```
print(str1.lower())

```

Exercise 5: Print str1 as title

Solution:

```
print(str1.title())

```

Exercise 6: Get a new string from str1 ‘DatTaa’ as ‘Data’

Solution:

```
new_str = str1.replace('DaTaa','Data')

print(new_str)

```

Exercise 7: Get a new string from str1 with exra ‘a’ removed from ‘DatTaa’

Solution:

```
new_str = str1[:-1]

print(new_str)

```

Exercise 8: Display date, month and year form 10-Jan-2020

Solution:

```
date_str = '10-Jan-2020'

d,m,y = date_str.split('-')

print("date :{0} month:{1} year:{2}".format(d,m,y))

```

Solution:

Exercise 9: Display ‘sample’ word from ‘ this is another sample string ‘

Solution:

```sample_string = ' this is another sample string '

new_word = sample_string.strip().split()[-2]

print(new_word)

```

Exercise 10: arr = “10,20,30,40,50,60,70”, get “50,60”

Solution:

```
arr = "10,20,30,40,50,60,70" # get "50,60"

new_str = ",".join(arr.split(',')[4:6])

print(new_str)

#using negative index
new_str = ",".join(arr.split(',')[-3:-1])

print(new_str)

```

Exercise 11: Find the sum of elements arr = “10,20,30,40,50,60,70”

Solution:

```
arr = "10,20,30,40,50,60,70"

total = sum(map(int,arr.split(',')))

print(total)

```

Exercise 12: From credit_str = “xxxx—-xxxx-8888——xxxx” get ‘8888’

Solution:

```
credit_str = "xxxx----xxxx-8888------xxxx"

new_credit_str = credit_str[credit_str.index('8'):credit_str.index('8') + len('8888')]

print(new_credit_str)

```

Exercise 13: From credit_str = “1234-5678-9878-0434” get ‘0’

Solution:

```
credit_str = "1234-5678-9878-0434"

new_str = credit_str.split("-")[-1]

print(new_str)

```

Exercise 14: From given list

gadgets = [“Mobile”, “Laptop”, 100, “Camera”, 310.28,

“Speakers”, 27.00, “Television”, 1000, “Laptop Case”, “Camera Lens”]

create separate lists of strings and numbers.

Solution:

```
gadgets = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00,
"Television", 1000, "Laptop Case", "Camera Lens"]

str_items = []
num_items = []

if isinstance(item, str):

str_items.append(item)

elif isinstance(item,int) or isinstance(item, float):

num_items.append(item)

print(str_items)

print(num_items)

```

Exercise 15: Given two strings check first is reverse of second. Ex ‘ABC’, ‘CBA’

Solution:

```
def is_reverse(s1, s2):

for i in range(len(s)):

if s1[i] != s2[len(s1)-i-1]:

return False

return True

s = "ABC"

s2 = "CBA"

s3 = 'abc'

print(is_reverse(s,s2)) #returns True

print(is_reverse(s,s3)) #returns False

```

Exercise 16: Given a strings check first and last words are same.

Ex: ” Apples should compared with Apples” => should print same

Solution:

```
given_string = " Apples should compared with Apples"

word_list = given_string.strip().split()

if word_list == word_list[-1]:
print("First and last words are same")

else:

print("First and last words are not same")

```

Exercise 17: From the given list calculate total scores.

student_scores =[‘Alex|75 50 90 80 90 70’,
‘Mary|76 72 71 68 85 69’,
‘John|69 67 68 71 68 67’,
‘Anne|80 69 59 82 71 81’,
‘Mark|79 81 74 71 69 73’
]

Solution:

```#display student name and total scores

student_scores =['Alex|75 50 90 80 90 70',
'Mary|76 72 71 68 85 69',
'John|69 67 68 71 68 67',
'Anne|80 69 59 82 71 81',
'Mark|79 81 74 71 69 73'
]

def student_total_scores(stud_scores):

for item in stud_scores:
f, s = item.split("|")
print(f,sum(map(int,s.split())))

#print(item)

student_total_scores(student_scores)

```

Exercise 18: write a function encrypt a given string,

input sample :

2) abc => abc
3) wwww => w4

Solution:

```def encrypt_mesage(s1):
ns = ""
next = 0
count = 1
for i in range(len(s1)):
#print(s1[i])
next += 1
if next < len(s1):

if s1[i] == s1[next]:
count += 1
else:
ns += s1[i]

if count > 1:
ns += str(count)
count =1
else:
#this should be the last
ns += s1[i]
if count >1:
ns += str(count)

return  ns

s2 = "abc"

s3 = "wwww"

print(encrypt_mesage(s1))

print(encrypt_mesage(s2))

print(encrypt_mesage(s3))

print(encrypt_mesage(s4))

output:
abca3d3bv2s2c4

abc

w4

abca2d2b2v2s2cd

```