Description

String in Python.

In Python it is called a string which is inside single or double qutation marks.

For Example:

'lapmos' is the as "lapmos".

Both are String in Python.

Assign String to a variable in python.

a = "lapmos"
print(a)

Output:

lapmos

Multiline String in Python Programming.

We can Write multiline string inside three single or double quotation mark.

For Example:
 

poem = """Twinkle twinkle little star.
How I wonder what you are.
Up above the world so high.
Like a diamond in the sky.
"""
print(poem)

Output:

Twinkle twinkle little star.
How I wonder what you are.
Up above the world so high.
Like a diamond in the sky.

Find the string length.

If we want to calculate the length of any string in Python, then we use the len().

a = "Hello! Coders"
print(len(a))

Output:

13

Check the string.

If we want to find out any character and any sub string in a string, then we use in keyword.

For Example:

Check if "Welcome" is present in the following statement:

a = "Hello Everyone! Welcome to lapmos.com"
print("Welcome" in a)

Output:

True

Slicing String in Python.

You can return a range of characters by using the slice syntax.

If a specific part of any string is to be accessed, then slicing is used in the string. 

Specify the start index and the end index, separated a colon, to return a part of the string. Get the character from position[2] to position[4](not included).

a = "Hello! Coders"
print(a[2:4]

Output:

ll

Slice from the start.

Slice any string without giving it a starting index. If we want to slice from the starting index to any index, then we can do like this.

a = "Hello! Coders"
print(a[:4])

Output:

Hell

Slice to the End.

By leaving out the end index, the range will go to end:

For Example:

a = "Hello!! Coders"
print(a[2:])

Output:

llo! Coders

Negative Indexing in Python.

Use negative indexes to start the slice from the end of the string.

For Example:

Get the characters:

From: "o" in "World!" [position -2]

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

Output:

orl

Modify Strings in Python Programming.

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

Uppercase in Python.

The upper() method returns the string in upper case.

For Example:

a = "lapmos"
print(a.upper())

Output:

LAPMOS

Lower case in Python.

The lower() methods returns the string in lower case:

a = "laPMOs"
print(a.lower())

Output:

lapmos

Remove Whitespace in Python.

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

For Exampe:

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

a = "  Hello! Coders "
print(a.strip()) # returns "Hello! Coders"

Output:

Hello! Coders

Replace string in Python

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

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

Output:

Tello, World!

Split String in Python.

The split() method returns a list where the text between the specified seprator becomes the list items. 

For Exampe:

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

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

Output:

['Hello', 'World!']

String Concatenation in Python programming.

To concatenate, or combine, two string you can use the + operator.

For Example:

Merge Variable "a" with variable "b" into variable "c".

a = "lap"
b = "mos"
c = a + b
print(c)

Output"

lapmos

Format Strings in Python Programming language.

We can not combine string and number like this:

For Example:

age = 34
a = "My name is DOY, I am " + age
print(a)

Output:

  a = "My name is DOY, I am " + age
TypeError: can only concatenate str (not "int") to str

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:

For Example:

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

age = 34
a = "My name is DOY, and I am {}"
print(a.format(age))

Output:

My name is DOY, and I am 34

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

qty = 3
itemno = 567
price = 49.95
my_order = "I want {} pieces of item {} for {} dollars"
print(my_order.format(quantity, itemno, price))

Output:

I want 3 pieces of item 567 for 49.95 dollars.

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

For 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))

Output:

I want to pay 49.95 dollars for 3 pieces of item 567

Escape Characters in Python Programming language.

Code Result
\' single Quote
\\ Backslash
\n New line
\r Carriage return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal Value
\xhh Hex Value

String methods in Python Programming language.

Method Description
capitalize() Converts the first character to uppercase.
casefold() Converts string into lower case.
center() Returns a centered string
count() Returns the number of tiems a specified value occurs in a string.
encode() Return an encoded version of the string.
endswith() Returns true if the string ends with the specified value.
expandtabs() Sets the tab size of the string.
find() Searched the string for a specified value and returns the position of where it was found.
format() Formats specified values in a string.
format_map() Formats spcified values in a string.
index() Searches the string for a specifed value and returns the position of the where it was found.
isalnum() Returns True if all characters in the string are alphanumeric.
isalpha() Returns True if all characters in the string are the alphabet.
isdecimal() Returns True if all characters in the string are decimals.
isdigit() Returns True if all characters in the string are digits.
isidentifier() Returns True if the string is an identifier.
islower() Returns True if all characters in the string are lower case.
isnumeric() Returns True if all charcters in the string are numeric.
isprintable() Returns True if all characters in the string are printable.
isspace() Returns True if all characters in the string are whitespaces.
istitle() Returns True if the string follows the rules of a title.
isupper() Returns True if all characters in the string are upper case.
join() Joins the elements of an iterable to the end of the string.
ljust() Return a left jutified version of the string.
lower() Coverts a string into lowercase.
lstrip() Return a left trim version of the string.
marketrans() Returns a translation table to be used in translations.
partition() Returns a tuple where the string is parted into three parts.
replace() Returns a string where a specified value is replaced with a specifed value.
rfind() Searches the string for a specified value and returns the last position of where it was found.
rindex() Searches the string for a specified value and returns the last position of where it was found.
rjust() Returns a right justified version of the string.
rpartition() Returns a tuple where the string is parted into three parts.
rsplit() Splits the string at the specified separtor, and returns a list.
rstrip() Returns a right trim version of the string.
split() Splits the string at the specifed separtor, and returns a list.
splitlines() Splits the string at the breaks and returns a list
startswith() Returns true if the string starts with the specified value.
strip() Returns a trimmed version of the string.
swapcase() Swaps cases, lowercase becomes uppercase can viceversa.
title() Converts the first charcter of each word to upper case.
translate() Returns a translated string.
upper() Converts a string into uppercase.
zfill() Fills the string with a specified number of 0 values at the beginning.

 

Comments

Login is mandatory to comment Please login

Recommended Posts

List and Tuple in Python Programming

List is a kind of data structure in Python which is mutable, changeable, ordered sequence. Tuples are used to store multiple items in a single variable.

Dictionary In Python | Method Of Dictionary

Dictionary is used to store data values in Key: Value pairs. A dictionary is a collection which is ordered, Changeable and do not allow duplicates.

Implement of All Method of String in Python Programming language

Implementation of all methods of string in python. How to implement of method on string.

Operators based Exercise 1 in Python Programming language.

All operators used for better understanding the python operators.

Sets in Python | Perform Set methods

A Set is an unordered collection data type which does not contain duplicates elements. A set is iterable and mutable data type.

Conditional Statement If elif else statement in Python

Like some situation comes in our real life in which we have to take some decision as to what we have to do next.