Tuesday, June 12, 2018

String in Python

What is String? 


String are immutable.

String is sequence of Unicode characters.

String can represent between single quotes or double quotes .

‘Hello worlds’ is same output as “Hello worlds”.

For multi-line string represent between triple quotes, “””or ‘’’.

Subsets of strings can be taken using the slice operators ([] and [:]).

Slice Operator indexes starting at 0 form beginning and -1 form ending.

Plus( + and , ) sigh is the string concatenation operator.

Asterisk(*) is the repetition operator .

The str use for datatypes conversion.

Example:

print(‘Hello World!’) # with Single Quotation mark

print(“Hello World!”) # With Double Quotation Mark 


Output:

Hello World!

Hello World!


Check Data Types: type() Function

Name =”Justseeker”

print(type(Name)) # Output: <class 'str'>

Get Character at Position 1

Name = “Justseeker”

print(Name[0]) # output: J

Sub-string: Get 4 to 9:

Name = “Justseeker”

print(Name[4 : 10]) # Output: seeker

Get Last Character to the String

print(Name[-1]) # Output: r

Get 4 to last:

print(Name[4 : ]) #Output: seeker



In-built : strip()


Remove any white spaces from the beginning or the end

Name = “ Hello Friends”

print(Name.strip()) #Output: Hello Friends


In-built : len()


Return length of String

Name = “ Hello Friends”

print(len(Name)) # Output: 13



In-built : lower()


Convert string to lower case

Name = “ Hello Friends”

print(Name.lower()) # Output: hello friends



In-built : upper()


Convert string to Upper Case

Name = “ Hello Friends”

print(Name.upper()) # Output: HELLO FRIENDS



In-built : replace()


Replace a string with another string

Name = “ Hello Friends”

print(Name.replace('H','J')) # Output: Jello Friends



In-built : split()


Spites string into sub-strings using instances of the separator:

Name = "Hello, World!"
print(Name.split(",")) # Output: ['Hello', ' World!']



In-built : casefold()


Create a lowercase string that is suitable for case insensitive comparisons

This is more aggressive then lower() function.

Name = “Justseeker”

print(Name.casefold()) #Output: justseeker



In-built :capitalize()


Return a capitalized version of the string.

It makes the first character have upper case and the rest lower.

A = “this Is A Strings”

print(A.capitalize()) # Output: This is a strings



In-built :title()


Return the title cased version of the string.

Every letter in the beginning of word is made upper case and all other made lower case.

A = “this Is A Strings”

print(A.title()) # Output: This Is A Strings



In-built :swapcase()


Return a new string in which all lower case characters are swapped to upper case and all upper case characters to lower.

A = “thIs Is A STRings”

print(A.swapcase()) # Output: ThiS iS a strINGS


There are many other thing in string we cover on later chapters

Prev: Number in python

Next: List in Python

No comments:

Post a Comment

Google+ Followers