Python string index, access, length, slice, split, loop, strip, replace, concatenate examples.

Learn python string defining, indexing, accessing elements, length, split, loop, strip, replace, slice, concatenate, repeat, finding offset, check digit or alphabet, lower to upper case and vice-versa, strings exercises and solutions.

Subscribe to earn a certificate from our online courses listed . Your low cost subscription will enable complete access to all , , to clear all online course requirements.

Define string & indexing elements

Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes for strings.
We can access string elements using index. The indexing starts from 0 i.e. index 0 will print the first character of the string, 1 will print the second character of the string and so on.
Let's write a function to demonstrate these features of string as in program below.

def main():
  S = 'spam'
  print ('single quote string is',S)
  S = "spam"
  print ('double quote string is',S)
  print (S[0],S[2])
  return S
  res = main()


single  quote  string  is spam
double  quote  string  is spam
s a

Length of string, concatenate strings

Length of a string in python can be determined using len library function. The len function calculates the length of the string starting from 1 where as string indexing starts from 0. Also we can concatenate multiple strings together using '+' to make another string. This is demonstrated in the below program. In this program when we called the main function we could concatenate all strings together to make the resultant string.

def main(s):
  return len(s)
  string = 'Hello'
  res = main(string)
  print('length of string ' + string + 'is: ' + str(res))


length of string Hello is: 5

Repeat, return multiple strings from function

In python you can repeat a string just by multiplying a number to the string. Also we can return multiple strings from a function. This is demonstrated in the below program.

def strRepeating(stri):
  stri = stri*3
  mystr = '='*3
  return stri,mystr
  mystring = "Hello"
  res1,res2 = strRepeating(mystring)


HelloHelloHello ===

Finding offset of a string

To Read Full Article

You need to subscribe & logged in


Want to contribute a new article? Write and upload your article information .


 Python Programming

 Linux Software

 C Programming

 Embedded Systems

 Python Programming

 Search code examples

, , , , , , , , , , , , , , , , , ,

 Search MCQs with answers

, , , , , , , , , , , , , , , , ,

 Online certificate courses

 Test your skills:online tests

 C Programming

 Python Programming

 Linux Software

 Quantitative Aptitude

 Embedded System Software