Python Mini Course - Course Notes: Part 3 (String) of 5

3) Python String

3.1) String Concatenation

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

Output:

Hello World

3.2) User Input

Python provide two inbuilt functions to read input from the keyboard:
- raw_input( prompt ) -- Used in Python v2
- input( prompt ) -- Used in Python v3

Note: Whatever you enter as input is converted into a string. If you enter an integer value, the input() function still converts it into a string - you need to explicitly convert it into an integer in your code using typecasting.

Name = input("Type Your name :")

To take two or more inputs in one input line, we can use the split() function.

name, age = input("enter your name and age :".split()
print(name)
print(age)

Output:

enter your name and age:Bob 27
Bob
27

split() - separates by spaces
split(",") - separates by comma

3.3) int() and str() function

The int() function converts the specified value into an integer number.
The str() function converts the specified value into a string.

Example:

first_number = int(input("Enter first number "))
second_number = int(input("Enter second number "))
Total = first_number + second_number
print("Total is " + str(Total))

Image: 7 + 7 = 14

3.4) String Formatting

Example using format() and place holder {}.

name = "James"
age = 33
print("Hello " + name + " your age is " + str(age)) # Ugly format
print("Hello {} your age is {}".format(name,age)) # Looks better

Image: Using Python format()

3.5) String Indexing

The index() method
- finds the first occurrence of the specified value
- raises an exception if the value is not found
- is almost the same as the find() method (the find() method returns -1 if the value is not found)

Syntax:
str.index(str, beg = 0 end = len(string))

Parameters:
str - specifies the string to be searched
beg - (optional) is the starting index (default is 0)
end - (optional) is the ending index (default equal to the length of the string)

Examples:

txt = "Hello, welcome to my world."
x = txt.index("welcome")
y = txt.index("e", 5 , 10)
print(x)
print(y)
print(txt.find("q"))
print(txt.index("q"))

Output:

7
8
-1
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(txt.index("q"))
ValueError: substring not found

Print the Value of any Particular Postion

#print 5th postion (counts from 0)
language = "Python"
print(language[4]) #result is o

#print last position
print(language[-1]) #result is n

3.6) String Slicing and Step Argument

String Slicing Syntax:
String[Start argument : Stop Argument -1]

Example - get characters from position 2 to position 5 (not included):
aString = "Hello World!"
print(aString[2:5])

Output:
llo

String Slicing with Stop Argument Syntax:
String[Start argument : Stop Argument -1 : step]

Example - display string from 0 to 11 by taking 2 steps:
aString = "Hello World!"
print(aString[0:11:2])

Output:
HloWrd

3.7) Basic String Methods

Python has a set of built-in methods that you can apply to strings.

len() function - gives the length of the string including spaces
lower() method - gives the string in lower case
upper() method - gives the string in upper case
title() method - capitalizes the 1st letter of the string
count() method - count of occurrences of a particular selected character

Examples:
name = "nIGel mANSell"
print(len(name))
print(name.lower())
print(name.upper())
print(name.title())
print(name.count("l"))

Output:
13
nigel Mansell
NIGEL MANSELL
Nigel Mansell
3

lstrip() method - returns a left trim version of the string

Syntax:
string.lstrip(characters)

Note: Space is the default leading character to remove.

Example 1:
txt = "          banana"
print("of all fruits", txt.lstrip(), "is my favourite")

Output 1:
of all fruits banana is my favourite

Example 2:
txt = ",,,rraaww...banana"
print(txt.lstrip(",.raw"))

Output 2:
banana

find() method finds the first occurrence of the specified value, and returns -1 if the value is not found

Syntax:
string.find(value, start, end)

Example:
###### 012345678901
print("Hello and welcome to my world".find("e", 5, 15))

Output:
11

replace() method replaces a specified phrase with another specified phrase

Syntax:
string.replace(oldvalue,newvalue,count)

Example:
# ..... 1 . 2 ............................... 3 .....
print("one one was a race horse, two two was one too".replace("one", "three", 2))

Output:
three three was a race horse, two two was one too

Comments