Jun 22, 2020

Strings in Python | Initializing | Deletion | Concatenation | Coding Winds |

STRINGS

Hello guys, today we will discuss about the data type, “STRINGS”. We have already discussed about how to initialize and know that data type.

String is a sequence of characters. In python, a string is a sequence of UNICODE character. Learn more about UNICODE character here, Python UNICODE.

Initializing Strings:

Strings are initialized by putting the character in between the inverted commas.

Look at the code’s output,


Accessing Strings:

We can access individual characters by indexing and a range of character by slicing. Index starts from 0.  To access a range of characters, we use slicing operator, ‘:’.

Trying to go out of the index will bring up IndexError.  We use only integer while indexing other than an integer will give TypeError.

Python also takes negative indexing, -1 will give out the last element, and -2 will give out the second last element and so on.


Output of the program is very important to check out,


Let’s check out the errors mentioned above,


The other one, 


Deletion of a string:

Strings are perpetual, i.e. we cannot make any change to the elements of the strings. Also we cannot delete elements of a string but we can surely delete the whole string by the keyword, del.



Concatenation of strings:

Merging of two or more strings into a single string is called concatenation.

+ And * helps us achieving concatenation. The + sign adds strings. The * sign multiplies the string.



Iteration

We can iterate through a string using for loop.



Note- We can use strings in built-in functions.

Like,


Escape Sequence:

Escape Sequence

Description

\newline

Backslash and newline ignored

\\

Backslash

\'

Single quote

\"

Double quote

\a

ASCII Bell

\b

ASCII Backspace

\f

ASCII Formfeed

\n

ASCII Linefeed

\r

ASCII Carriage Return

\t

ASCII Horizontal Tab

\v

ASCII Vertical Tab

\ooo

Character with octal value ooo

\xHH

Character with hexadecimal value HH


Examples, 


The format () method

The format () method with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces { } as placeholders or replacement fields which get replaced.


We can also use it to with other purposes, string formatting by format().

There are many other methods available with the string element. Check all of them out by clicking here, python string methods


Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.


Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!



No comments:

Post a Comment