Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python Unit 3 Part 2

Second
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Unit 3 Part 2

Second
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Strings

A string is a sequence of characters. A character is simply a symbol. For example, the English
language has 26 characters. Computers do not deal with characters, they deal with numbers
(binary). Even though you may see characters on your screen, internally it is stored and
manipulated as a combination of 0's and 1's.

This conversion of character to a number is called encoding, and the reverse process is decoding.
ASCII and Unicode are some of the popular encoding used.

String Literals
String literals in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')
Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:

Example
a = "Hello"
print(a)
»

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

a = """Python is a compiled interpreted


language. It is having both the properties"""
print(a)
Or three single quotes:

Example
a = Python is a compiled interpreted
language. It is having both the properties '''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.
Python string length | len()

len() function is an inbuilt function in Python programming language that returns the length of
the string.
Syntax:
len(string)
Parameters:
It takes string as the parameter.
Return Value:
It returns an integer which is the length of the string.
Output
str = "python"
print(len(str))
Output:
6

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, Python does not have a character data type, a single
character is simply a string with a length of 1. Square brackets can be used to access elements of
the string.

Example
Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Slicing
We can return a range of characters by using the slice syntax. Specify the start index and the end
index, separated by a colon, to return a part of the string.

Example
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters from position 5 to position 1, starting the count from the end of the string:

b = "Hello, World!"
print(b[-5:-2])

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

String Methods
Python has a set of built-in methods that you can use on strings.

Example
The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Example
The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

Example
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Example
The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

String Format
We learned in the previous that we cannot combine strings and numbers directly or with the help
of ‘+’ operator.
Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:

Example
Use the format() method to insert numbers into strings:

age = 36
txt = "My name is Raj, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} rupees."
print(myorder.format(quantity, itemno, price))

We can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

The repetition operator is denoted by a '*' symbol and is useful for repeating strings to a certain
length.
Example:

str = 'Python program'

print(str*3)

The above lines of code will display the following outputs:


Python programPython programPython program

Similarly, it is also possible to repeat any part of the string by slicing:

Example:
str = 'Python program'

print(str[7:9]*3) #Repeats the seventh and eighth character three times

prprpr

You might also like