Python Programming
About Lesson

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

Example
str = “Welcome to Python.”
print(len(str))

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

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

Example
str = ” Welcome to Python. “
print(str.strip())

The lower() method returns the string in lower case:
str = “Welcome to Python.”
print(str.lower())

The upper() method returns the string in upper case:
str = “Welcome to Python.”
print(str.upper())

The replace() method replaces a string with another string:
str = “Welcome to Python. “
print(str.replace(“P”, “J”))

The split() method splits the string into substrings if it finds instances of the separator:
str = “Welcome to Python.”
print(str.split(” “))

Check String
To check if a certain phrase or character is present in a string, we can use the keywords ‘in’ or ‘not in’. This checking would return a True or False

#Example
str = “Welcome to Python.”
chk=”Py” in str
print(chk)

Check if the phrase “ain” is NOT present in the following text:
str = “Welcome to Python.”
chk=”Hai” not in str
print(chk)

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

Example
Merge variable a with variable b into variable c:
x = “Welcome”
y = “Python”
z =x+y
print(z)

To add a space between them, add a ” “:
x = “Welcome”
y = “Python”
z =x+” “+y
print(z)

#Example
x = “Welcome”
y =x+” Python”
print(y)

String Format
We cannot combine strings and numbers like this:

Example
age = 20
x =”My age is:”+age
print(x)

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 = 20
x =”I am {} years old”
print(x.format(age))

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

Example
name=”sai”
age = 20
qual=”BSc”
str=”My name is {} of age {}, completed {}”
print(str.format(name,age,qual))

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

Example
name=”sai”
age = 20
qual=”BSc”
str=”My name is {2} of age {1}, completed {0}”
print(str.format(qual,age,name))

You cannot copy content of this page