Tutorials

0
Python has many native datatypes. Here are the important ones:
  1. Booleans
  2. Numbers
  3. Strings
  4. Bytes
  5. Lists
  6. Tuples
  7. Sets
  8. Dictionaries

String

String is a collection of characters. In order to assign string to a variable, the following code snippet works.

a = "This is a string."

b = 'This is another string.'

Anything written in double quotes (" ") or single quotes (' ') is considered string.
In order to find length of a string, use len() function.

a = "This is a string."
print (len(a))

The output is 17 (total number of characters in a string). A string is indexed from 0 i.e. in variable 'a', 'T' is 0, 'h' is 1 and '.' is 16. In order to extract part of a string, string splitting is used.

a = "This is a string."
print (a[0:6])
print (a[5:-2])
print (a[1:])
print (a[:6])

OUTPUT
This i
is a strin
his a string.
This i

a[0:6] => Start from 1st character ('T') and

 end at 6th character ('i').
a[5:-2] => Start from 6th character ('i') and end at 2nd last character ('n').
a[1:] => Start from 2nd character ('h') and print the entire string after that.
a[:6] => Start from beginning of string and end at 6th character('i').

NOTE: The indexing can also be negative, i.e.

 -2 indicates the second last character.




Post a Comment

 
Top