String in python
•String can be treated as contiguous set character,String can be
enclosed with single or double quote.
» index starts from zero, hence to print 1st character in a string
Code:
name = program
print(name[0])
output:
p
•To print from 2nd character to 6th character then,
Code:
name = programming
print(name[1:6])
output:
rogra
•To print from 3rd character to end of the string then,
Code:
name = programming
print(name[2:])
output:
ogramming
•Len()
The len() function used to find the length of the string
Code:
name = program
print(len(name))
output:
7
• + operator is used to concatenate string values.
The below program concatenates the values in firstname and
lastname and print it as the ouput.
Code:
firstname = ‘hello’
lastname = ‘world’
print( firstname + lastname)
output:
hello world
»note: use .strip() function to remove the spaces.
Print(firstname.strip() + lastname.strip())
String-upper and lower case
Upper and lower methos can be use to convert all the
characters in a string to upper case or lower case respectively
The below program accepts a string value and prints all
characters in upper case
Code:
string= program
print(string.upper())
Output:
PROGRAM
String-reverse
Reversing the string can be done by using the slice operator to
go one step back from the end by specifying -1
The below program accepts a string value and prints the reverse
value
Code:
inputstring = input()
print( inputstring[::-1])
output:
program
margorp