st copy
st copy
Strings
• A string is a sequence of characters in order. A character is anything
you can type on the keyboard in one keystroke, like a letter, a number,
or a backslash.
• Strings can be created by enclosing characters inside a single quote or
double-quotes. Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.
• Strings can have spaces: "hello world".
word1='Python'
word2='Python Programming'
word3="Python Programming"
word4="""Python is a Programming......
Language"""
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Accessing String Characters
w='Python'
path="c:\\new\\text.dat"
path1="c:\\raw\\book.dat"
word1="\\n is new line character"
word2="\\t is tab space character"
print(path)
print(path1)
print(word1)
print(word2)
Raw Strings
• Raw strings suppresses or ignores escape sequences. Raw strings are
represented by using r or R before a string.
path=r"c:\new\text.dat"
path1=R"c:\raw\book.dat"
word1=r"\n is new line character"
word2=R"\t is tab space character"
print(path)
print(path1)
print(word1)
print(word2)
Concatenation of Strings
• Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python.
a='Python'
b='Programming'
c=a+b
d=('python' 'programming')
e='Python' 'programming'
print(c, a+b)
print(a*5)
print((a+b)*3)
print(d)
print(e)
String Membership Test
a='Python'
print('t' in a)
print('t' in 'Python')
print('T' in a)
print('th' not in a)
Slicing
• To get set of characters from a string, we can use the slicing method
like
variable name[start : end ]
• By default the step value is +1(positive) and is optional. Start and end
are similar to normal slicing.
• If the step value is negative, then extraction starts from the end and
prints in the reverse order.
Extended Slicing
word=‘Hello World’
H e l l o W o r l d
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Slicing
Output Description
Operation
word[0:4:1] Hell get first four characters of the word
>>> S = ‘hello'
>>> S[0] = 'c' # Raises an error!
TypeError: 'str' object does not support item
assignment
>>>S=“world”
>>>print (S)
world
Updating Strings
• We can concatenate another string to the existing string. For example,
>>> S =“hello”
>>>S= S + ‘world!'
# To change a string, make a new one
>>> S
‘helloworld!'
>>> S=‘hello’
>>> del S[1]
TypeError: 'str' object doesn't support item deletion
>>> del S
>>> S
...
Name Error: name ‘S' is not defined
Sample Program 1
• Write a program to find number of letters in a string or calculate the
length of a string.
word='Python Programming'
count=0
for i in word:
count=count+1
print("Length of the string1 : ", count)
Sample Program 2
• Write a program to find number of repeated letters in a string.
word='Python Programming'
count=0
for i in word:
if i=='o' or 'O':
count=count+1
print(" 'o' is repeated", count, "times")
Sample Program 3
• Write a program to find number of vowels in a string.