0% found this document useful (0 votes)
5 views23 pages

String

In Python, strings are created using single, double, or triple quotes and are treated as sequences of characters, with indexing starting from 0. Strings are immutable, meaning they cannot be changed after creation, and various operations such as concatenation, repetition, and membership testing can be performed. Python also provides numerous built-in string functions for manipulation, formatting, and checking properties of strings.

Uploaded by

disha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

String

In Python, strings are created using single, double, or triple quotes and are treated as sequences of characters, with indexing starting from 0. Strings are immutable, meaning they cannot be changed after creation, and various operations such as concatenation, repetition, and membership testing can be performed. Python also provides numerous built-in string functions for manipulation, formatting, and checking properties of strings.

Uploaded by

disha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

String in Python (sequence Type)

In python, strings can be created by enclosing the character or the sequence of characters
in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to
create the string.
It is sequence type data type.

Syntax:

str1 = 'Hello Python'

str2 = "Hello Python"

str3 = '''this is
Python
Multi statements string '''

Str4 = 'p'

In python, strings are treated as the sequence of characters which means that python
doesn't support the character data type instead a single character written as 'p' is treated as
the string of length 1.

Python Multiline String


We can also create a multiline string in Python. For this, we use triple double
quotes """ or triple single quotes ''' . For example,

# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)
Output

Never gonna give you up


Never gonna let you down

In the above example, anything inside the enclosing triple quotes is one
multiline string.

Python String indexing


Like other languages, the indexing of the python strings starts from 0. For example, the
string "HELLO" is indexed as given in the below figure.
str="HELLO"

str[0]=H
str[1]=E
str[4]=O

Python allows negative indexing for its sequences.


The index of -1 refers to the last item, -2 to the second last item and so on.

str[-1]=O
str[-2]=L
str[-4]=E
A string can only be replaced with a new string since its content cannot be partially
replaced. Strings are immutable in python.
str[0] = "B" ☒ can´t replace a single character in a string

str = "BYE" ☑ can replace a new string

Python String Operators


Operator Description

+ It is known as concatenation operator used to join the strings.

* It is known as repetition operator. It concatenates the multiple copies of the same


string.

[] It is known as slice operator. It is used to access the sub-strings of a particular


string.

[:] It is known as range slice operator. It is used to access the characters from the
specified range.

in It is known as membership operator. It returns if a particular sub-string is present


in the specified string.

not in It is also a membership operator and does the exact reverse of in. It returns true if
a particular substring is not present in the specified string.

r/R It is used to specify the raw string. To define any string as a raw string, the
character r or R is followed by the string. Such as "hello \n python".

% It is used to perform string formatting. It makes use of the format specifies used in
C programming like %d or %f to map their values in python.
Example - Working with String Operators
Examples:

str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.
print(r'Hello\n world') # prints Hello\n world as it is written
print("The string str1 : %s"%(str1)) # prints The string str : Hello

Output:

HelloHelloHello
Hello World
o
ll
False
False
Hello\n world
The string str1 : Hello

Python String Operations


Many operations can be performed with strings, which makes it one of the
most used Data Type in Python.

1. Compare Two Strings


We use the == operator to compare two strings. If two strings are equal, the
operator returns True . Otherwise, it returns False .

For example,
str1 = "Hello, world!"
str2 = "I love Swift."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Run Code

Output

False
True

In the above example,

1. str1 and str2 are not equal. Hence, the result is False .

2. str1 and str3 are equal. Hence, the result is True .

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.

greet = "Hello, "


name = "Riya"

# using + operator
result = greet + name
print(result)

# Output: Hello, Riya


In the above example, we have used the + operator to join two
strings: greet and name .

3. Iterate Through a Python String

We can iterate through a string using a for-loop.


For example,
word = 'Hello'

# iterating through greet string


for letter in word:
print(letter)

Output

H
e
l
l
o

4. Python String Length

In Python, we use the len() method to find the length of a string.


For example,
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5
5. String Membership Test

We can test if a substring exists within a string or not, using the keyword in .
print('a' in 'program') # True
print('at' not in 'battle') # False

Python String functions


Python provides various in-built functions that are used for string handling.
Those are

 len()
 lower()
 upper()
 replace()
 join()
 split()
 find()
 index()
 isalnum()
 isdigit()
 isnumeric()
 islower()
 isupper()

len()
In python string len() function returns length of the given string.
Syntax:
len(string)

Example

str1="Python Language"
print(len(str1))

Output: 15

lower ()
In python, lower() method returns all characters of given string in lowercase.
Syntax:

str.lower()

Example

str=”PyTHOn”
print(str.lower())
Output:

python

upper ()
In python upper() method converts all the character to uppercase and returns a
uppercase string.
Syntax:

str.upper()
Example

str=”PyTHOn”
print(str.upper())
Output:

PYTHON

replace()
In python replace() method replaces the old sequence of characters with the
new sequence. If the optional argument count is given, only the first count
occurrences are replaced.
Syntax:

str.replace(old, new[, count])


old : An old string which will be replaced.
new : New string which will replace the old string.
count : The number of times to process the replace.

Example

str = "Java is Object-Oriented and Java is Portable "


# Calling function
str2 = str.replace("Java","Python") # replaces all the
occurences
# Displaying result
print("Old String: \n",str)
print("New String: \n",str2)

str3 = str.replace("Java","Python",1) # replaces first occurance


only
# Displaying result
print("\n Old String: \n",str)
print("New String: \n",str3)

str4 = str1.replace(str1,"Python is Object-Oriented and


Portable")
print("New String: \n",str4)
Output:

python
PYTHON
Old String:
Java is Object-Oriented and Java is Portable

New String:
Python is Object-Oriented and Python is Portable

Old String:
Java is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Java is Portable

New String:
Python is Object-Oriented and Portable

join()
Python join() method is used to concat a string with iterable object. It returns a
new string which is the concatenation of the strings in iterable. It allows various
iterables like: List, Tuple, String etc.
Syntax:

str.join(sequence)

Example

str1 = ":" # string


str2 = "NNRG" # iterable object
str3= str1.join(str2)
print(str3)
Output:

N:N:R:G

split()
In python split() method splits the string into a comma separated list. It
separates string based on the separator delimiter. The string splits according to
the space if the delimiter is not provided.
Syntax:

str.split([sep=”delimiter”])
sep: It specifies the delimiter as separator.

Example

str1 = "Java is a programming language"


str2 = str1.split()
# Displaying result
print(str1)
print(str2)
str1 = "Java,is,a,programming,language"
str2 = str1.split(sep=',')
# Displaying result
print(str1)
print(str2)
Output:

Java is a programming language


['Java', 'is', 'a', 'programming', 'language']
Java, is, a, programming, language
['Java', 'is', 'a', 'programming', 'language']

find()
In python find() method finds substring in the whole string and returns index of
the first match. It returns -1 if substring does not match.
Syntax:

str.find(sub[, start[,end]])
sub :it specifies sub string.
start :It specifies start index of range.
end : It specifies end index of range.
Example

str1 = "python is a programming language"


str2 = str1.find("is")
str3 = str1.find("java")
str4 = str1.find("p",5)
str5 = str1.find("i",5,25)
print(str2,str3,str4,str5)
Output:

7 -1 12 7

index()
In python index() method is same as the find() method except it returns error on
failure. This method returns index of first occurred substring and an error if
there is no match found.
Syntax:

index(sub[, start[,end]])
sub :it specifies sub string.
start :It specifies start index of range.
end : It specifies end index of range.

Example

str1 = "python is a programming language"


str2 = str1.index("is")
print(str2)
str3 = str1.index("p",5)
print(str3)
str4 = str1.index("i",5,25)
print(str4)
str5 = str1.index("java")
print(str5)
Output:

7
12
7
Substring not found

isalnum()
In python isalnum() method checks whether the all characters of the string is
alphanumeric or not. A character which is either a letter or a number is known
as alphanumeric. It does not allow special chars even spaces.
Syntax:

str.isalnum()

Example

str1 = "python"
str2 = "python123"
str3 = "12345"
str4 = "python@123"
str5 = "python 123"
print(str1. isalnum())
print(str2. isalnum())
print(str3. isalnum())
print(str4. isalnum())
print(str5. isalnum())
Output:

True
True
True
False
False

isdigit()
In python isdigit() method returns True if all the characters in the string are
digits. It returns False if no character is digit in the string.
Syntax:

str.isdigit()

Example

str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23
str6 = “/u00BD” # 1/2
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
print(str4.isdigit())
print(str5.isdigit())
print(str6.isdigit())
Output:

True
False
False
False
True
False

isnumeric()
In python isnumeric() method checks whether all the characters of the string are
numeric characters or not. It returns True if all the characters are numeric,
otherwise returns False.
Syntax:

str.isnumeric()

Example
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23
str6 = “/u00BD” # 1/2
print(str1.isnumeric())
print(str2.isnumeric())
print(str3.isnumeric())
print(str4.isnumeric())
print(str5.isnumeric())
print(str6.isnumeric())
Output:

True
False
False
False
True
True

islower()
In python string islower() method returns True if all characters in the string are
in lowercase. It returns False if not in lowercase.
Syntax:

str.islower()

Example

str1 = "python"
str2="PytHOn"
str3="python3.7.3"
print(str1.islower())
print(str2.islower())
print(str3.islower())
Output:
True
False
True

isupper()
In python string isupper() method returns True if all characters in the string are
in uppercase. It returns False if not in uppercase.
Syntax:

str.isupper()

Example

str1 = "PYTHON"
str2="PytHOn"
str3="PYTHON 3.7.3"
print(str1.isupper())
print(str2.isupper())
print(str3.isupper())
Output:

True
False
True

Escape Sequences in Python


The escape sequence is used to escape some of the characters present
inside a string.
Suppose we need to include both a double quote and a single quote inside a
string,

example = "He said, "What's there?""

print(example) # throws error

Since strings are represented by single or double quotes, the compiler will
treat "He said, " as a string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \ in Python.

# escape double quotes


example = "He said, \"What's there?\""

# escape single quotes


example = 'He said, "What\'s there?"'

print(example)

# Output: He said, "What's there?"

Here is a list of all the escape sequences supported by Python.

Escape Sequence Description

\\ 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

Character with hexadecimal


\xHH
value HH

Python String Formatting (f-Strings)


Python f-string makes it easy to print values and variables.
For example,
name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}')

Output
Cathy is from UK

Here, f'{name} is from {country}' is an f-string.


This new formatting syntax is powerful and easy to use.

Python String Interpolation


String interpolation is a process substituting values of variables into
placeholders in a string. For instance, if you have a template for saying hello
to a person like "Hello {Name of person}, nice to meet you!", you would like to
replace the placeholder for name of person with an actual name. This process
is called string interpolation.

f-strings
Python 3.6 added new string interpolation method called literal string
interpolation and introduced a new literal prefix f . This new way of formatting
strings is powerful and easy to use. It provides access to embedded Python
expressions inside string constants.
Example 1:

name = 'World'
program = 'Python'
print(f'Hello {name}! This is {program}')

When we run the above program, the output will be

Hello World! This is Python


In above example literal prefix f tells Python to restore the value of two string
variable name and program inside braces {} . So, that when we print we get
the above output.
This new string interpolation is powerful as we can embed arbitrary Python
expressions we can even do inline arithmetic with it.

Example 2:

a = 12
b = 3
print(f'12 multiply 3 is {a * b}.')

When we run the above program, the output will be

12 multiply 3 is 36.

In the above program we did inline arithmetic which is only possible with
this method.

%-formatting
Strings in Python have a unique built-in operation that can be accessed with
the % operator. Using % we can do simple string interpolation very easily.
Example 3:

print("%s %s" %('Hello','World',))

When we run the above program, the output will be

Hello World
In above example we used two %s string format specifier and two
strings Hello and World in parenthesis () . We got Hello World as
output. %s string format specifier tell Python where to substitute the value.
String formatting syntax changes slightly, if we want to make multiple
substitutions in a single string, and as the % operator only takes one argument,
we need to wrap the right-hand side in a tuple as shown in the example
below.
Example 4:

name = 'world'
program ='python'
print('Hello %s! This is %s.'%(name,program))

When we run the above program, the output will be

Hello world! This is python.

In above example we used two string variable name and program . We wrapped
both variable in parenthesis () .

It’s also possible to refer to variable substitutions by name in our format string,
if we pass a mapping to the % operator:
Example 5:

name = 'world'
program ='python'
print(‘Hello %(name)s! This is %(program)s.’%(name,program))

When we run the above program, the output will be

Hello world! This is python.


This makes our format strings easier to maintain and easier to modify in the
future. We don’t have to worry about the order of the values that we’re
passing with the order of the values that are referenced in the format string.

Str.format()
In this string formatting we use format() function on a string object and
braces {} , the string object in format() function is substituted in place of
braces {} . We can use the format() function to do simple positional
formatting, just like % formatting.
Example 6:

name = 'world'
print('Hello, {}'.format(name))

When we run the above program, the output will be

Hello,world

In this example we used braces {} and format() function to


pass name object .We got the value of name in place of braces {} in output.
We can refer to our variable substitutions by name and use them in any order
we want. This is quite a powerful feature as it allows for re-arranging the order
of display without changing the arguments passed to the format function.

Example 7:

name = 'world'
program ='python'
print('Hello {name}!This is{program}.'.format(name=name,program=program))

When we run the above program, the output will be


Hello world!This is python.

In this example we specified the variable substitutions place using the name
of variable and pass the variable in format() .

You might also like