Strings in Python


 String

        In Python strings are arrays of bytes representing Unicode characters. However Python does not have a character data type , a single character is simply string with a length of 1. Square brackets can be used to access elements of the string.

Strings are created by enclosing various characters within quotes. Python does not distinguish between single quotes and double quotes.

Strings in Python can be created using single quotes and double quotes or even triple quotes.


Example

var1="hello python"

var2="welcome to technical guptaji"

print(var1)

print(var2)

Output

hello python

welcome to technical guptaji


String Length

         len() function is an built-in function in Python programming language that returns the length of the string or the number of character in the string.

Blank symbol and special characters are considered in the length of the string.


Syntax

len(string)

Example

string1="python"

print(len(string1))

string2="hello python!"

print(len(string2))

Output

6

13

String Concatenation

         Concatenation means joining two operands. The process of merging or combining two or more strings is called string concatenation. For example one string would be "hello" and other would be "python". When you use concatenation to combine them it becomes "hello python".

In order to merge two strings into a single object you may use the "+" operator.

Example 1

str1="hello"

str2="python"

str3=str1+str2        # concatenate two strings

print(str3)

Output

hellopython

Example 2

>>> print("technical"+"guptaji")

technicalguptaji                                                                    # output

>>> print("red"+3)

TypeError : Can not concatenates "str" and "int" objects.        # output


To make this possible we can convert the number into a string using the appropriate function. We use to do this by the str() function.

Example

>>> print("red"+str(3))

Output

red3

String Repetition

     Sometimes we need to repeat the string in the program, and we can do this easily by using the repetition operator in Python.

The repetition operator is denoted by "*" symbol and is useful repeating strings to a certain length.

Example

string="python program"

print(string*3)                  # repeating string 3 times

Output

python programpython programpython program

String Slicing

     To access a range of characters in the string, method of slicing is used. Slicing in a string is done by using a slicing operator colon (:).

Example

string="pythonforbtech"

print(string)

# printing 3rd to 11th character

print(string[3:12])

# printing character between 3rd to 2nd last

print(string[3:-1])

Output

pythonforbtech

honforbte

honforbtec

Note : It is also possible to repeat any part of the string by slicing.

Example

string="pythonprogram"

# repeat the 7th and 8th characters 3 times

print(string[7:9]*3)

Output

rororo












No comments:

Post a Comment