Strings and list in python

Strings:

If alphanumeric characters are enclosed in single or double quotation marks, it indicates a string.
For example,
S1='hello'
S2='hai'
Print (type (S1))
#and your output will be str

Indexing:

It is used to extract a single character from a string.
For example,
S='hello'
print (S[1])
#and your output will be e
#e is present in the location given in input

Slicing:

It is used for printing a subset of the string.
For example,
S='Good day'
print (S[0:3])
#and your output will be Goo
#the characters present from 0th to 2nd(n-1) position is printed

Other functions:

1)len(S)-Used to find the length of the string .i.e.the number of characters in the string.
2)lower(S)-Used to print the string in lower case.
3)upper (S)-Used to print the string in upper case.
4)replace (S)-Used to replace the characters in a string.

Sample problems:

Problem-1
To reverse a string
Input
S='Good day'
k=S[::-1]
print (k)
#here S[-1]=y
Output
yad dooG

Problem-2
To find the number of vowels present in the given word.
Input
S='hello world'
U='aeiou'
Count=0
for i in range (Len(S)):
   if S[i] in U:
     Count=Count+1
   else:
     Continue
Output
3

List:

A list is a collection of elements of any data type. A list is mutable.
Syntax for list include,
  • Square bracket
  • Each term separated by comma 
We can perform all the above operations like indexing, slicing in list too. 
Example,

Code :
L=[1,2,3]
print(type(L))
print (L[1])
print (L)
print (len(L))
print (l[0:2])

Output
int
2
[1,2,3]
3
[1,2]

Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python