Strings

 

Strings

 

In Python, String class is one of the regular Data type. String can vary from a Single Character to Multiple Characters of any length. Everything is considered as String only and class name is str. There is no separate Character Data type. String is Considered as Sequence of characters.

 

But String is Immutable that means the individual Character in a String cannot be changed. It is possible to access the individual Characters in a string using INDEX which can take values from 0 to (Length - 1), where Length is no. of characters in the String and the Index value is always an Integer. The Index value can take Negative values also. If Index value is -1, it denotes the Last character and (-Length) is the First character.

 

Create a String

 

s='My String'

s1="Another one"

s2="'This is also possible"'

s3="""The Final Type"""

 

Yes, it is possible to create with Single Quotes, Double Quotes , Triple single Quotes and Triple double Quotes. But whichever type we start with, we should end with the same. It cannot be mixed.

 

Accessing Individual Characters

 

s='My String'

s1="Another one"

s2="'This is also possible'"

s3="""The Final Type"""

print(s[4])

print(s1[8])

print(s2[-1])

print(s3[0:5])

 

Output

t

o

'

The F

The above are few examples for the ways in which the Individual characters are accessed. As already discussed we can give Negative Index also. In Index, Using [0:5] is called Slice Operator, which means the Characters from 0 to 4 is retrieved. That is if 0:n is given, it means from the start character to n-1 Characters are retrieved. For Slice Operator it is possible to give both the Start and End value, Start value alone, End value alone or no value also. If just Start value is given that means from that Character till End. If just End value is specified means , from the Beginning to till the End value-1 specified. And if no value is given means from Start to Last.

 

Change or Delete

 

since String is immutable, Changing a particular character or Deleting it is not allowed, using them in program will generate an Error

s1[4]='g'

del s2[5]

 

The above kind are not allowed. But it is possible to delete an entire string using DEL method.

 

Example,

del s3

 

Operators Possible on String Class

 

While + operator Concatenates 2 string , * operator repeats 'n' times the given string.

 

Example

If we want to combine 2 strings that are in Multiple Lines, then use the Parenthesis and putting them together like shown

 

s='My String'

s1="Another one"

s2="'This is also possible'"

s3="""The Final Type"""

s4=s+s1

print(s4)

s5=s3*5

print(s5)

s6=("This is First line""And this is Next one")

print(s6)

 

Output

My StringAnother one

The Final TypeThe Final TypeThe Final TypeThe Final TypeThe Final Type

This is First lineAnd this is Next one

 

Iterating through the String Data

 

We can use Loop statement to iterate through the String

 

Example

s='My String'

s1="Another one"

s2="'This is also possible'"

s3="""The Final Type"""

s4=s+s1

print(s4)

s5=s3*5

print(s5)

s6=("This is First line""And this is Next one")

print(s6)

s7=s1+s2

c='o'

co=0

for ch in s6:

                if ch ==c:

                                co+=1

print("The Character",c," appears",co," times")

 

Output

My StringAnother one

The Final TypeThe Final TypeThe Final TypeThe Final TypeThe Final Type

This is First lineAnd this is Next one

('The Character', 'o', ' appears', 1, ' times')

 

Membership Operator

 

'in' and 'not in' are the 2 Membership operators. It checks for a Sub string in a string. If found returns True else False.

 

'a' in s

"b" not in s1

 

Output

False

True

 

Built in Functions of String class

 

enumerate() - this function enumerates the given string as a Tuples of the character and its position.

 

len()   - returns the length of the String

 

Example

 

s="Hello world"

en=list(enumerate(s))

print(en)

print(len(s))

 

Output

[(0, 'H'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o'), (5, ' '), (6, 'w'), (7, 'o'), (8, 'r'), (9, 'l'), (10, 'd')]

11

 

Formatting Strings

Escape Sequence Characters

 

Few Characters when used in String may generate Error, like single quotes, double quotes etc., to avoid these errors , we can Escape Sequence Characters. This is same as that of in C or C++ Language. '\' backslash along with a Character is called Escape Sequence Character. This is used inside the String to print non printable characters , say for example we want to display Hai, "What's your Name?". When we give it in a print statement as this,

 

print("Hai ,"What's your Name?"")

 

we will get an error. It will generate an Invalid Syntax error , because the Interpreter will get confused with the number of Quotes used. To avoid getting error, we can use Escape Sequence Character. Then they will print properly.

 

print("Hai ,\"What\'s your Name?\"")     or

print("Hai ,"What's your Name?""')

 

in the second case we have used triple quotes at the Ends and normal quotes wherever required.

 

Few Escape Sequence Characters

 

\n      -   used for New line

\a      -   for alert sound

\b      -   for Backspace character

\f       -   for form feed    (New Sheet)

\r       -   for Carriage return

\t       -   tab space horizontal

\v      -   tab space vertical

\ooo  -   character of octal value oo

\xHH  -   character of Hexa Decimal                  value HH

 

Raw string that ignores escape sequence

 

Some times we may require to display whatever given inside the Brackets and not as Escape sequence characters. For this we can use Raw string, the format is , 'r' or 'R' in front implicating Raw string

 

print("This is \x61 \nGood Example")

print(r"This is \x61 \nGood Example")

 

Replace Method

 

Though change of string is not allowed , we can use in built method 'Replace' to replace a Sub string with in a string.

 

s="I am Studying Python programming"

print(s)

s1=s.replace("Studying","undergoing")

s=s1

print(s)

Output

I am Studying Python programming

I am undergoing Python programming

 

 

Built-in methods for strings data class

 

All string methods returns new values only, if the Return data type is String. They do not change the original string, as Strings are immutable. If the Return Data type Boolean then normally they are used in Comparison Statements.

No comments:

Post a Comment