Casting and Strings in Python

   Python Casting

Specify a Variable Type


There may additionally be instances when you prefer to specify a kind on to a variable. This can be completed with casting. Python is an object-orientated language, and as such it makes use of training to outline facts types, along with its primitive types.

Casting in python is consequently accomplished the use of constructor functions:


  • int( ) - constructs an integer quantity from an integer literal, a drift literal (by eliminating all decimals), or a string literal (providing the string represents a entire number)
  • float( ) - constructs a waft wide variety from an integer literal, a flow literal or a string literal (providing the string represents a glide or an integer).
  • str( ) - constructs a string from a vast range of facts types, which include strings, integer literals and flow literals.

Example:-

        Integers:

        x = int(1)             # x will be 1
        y = int(2.8)         # y will be 2
        z = int("3")         # z will be 3

                            Try it Yourself»»

Example:-

        Floats:

        x = float(1)                 # x will be 1.0
        y = float(2.8)             # y will be 2.8
        z = float("3")             # z will be 3.0
        w = float("4.2")        # w will be 4.2

                            Try it Yourself»»


Example:-Casting and Strings in Python

        Strings:

        x = str("s1")         # x will be 's1'
        y = str(2)             # y will be '2'
        z = str(3.0)          # z will be '3.0'

                            
Try it Yourself»»



Python Strings

Strings


Strings in python are surrounded by means of both single citation marks, or double citation marks.

    'hello' is the identical as "hello".

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

Example:-

        print("Hello")
        print('Hello')

                            Try it Yourself»»


Assign String to a Variable


Assigning a string to a variable is executed with the variable title accompanied by means of an equal signal and the string:

Example:-

        a = "Hello"
        print(a)

                        Try it Yourself»»

Multi-line Strings


You can assign a multi-line string to a variable via the use of three quotes:

Example:-

        You can use three double quotes:

        a = """Lorem ipsum dolor take a seat amet,
        consectetur adipiscing elit,
        sed do eiusmod tempor incididunt
        ut labore et dolore magna aliqua."""
        print(a)

                            Try it Yourself»»

Or three single quotes:

Example:-

        a = '''Lorem ipsum dolor sit down amet,
        consectetur adipiscing elit,
        sed do eiusmod tempor incididunt
        ut labore et dolore magna aliqua.'''
        print(a)

                            Try it Yourself»»

Note: In the result, the line breaks are inserted at the equal role as in the code.




Strings are Arrays


Like many different famous programming languages, strings in Python are arrays of bytes representing Unicode characters.

However, Python does now not have a personality statistics type, a single personality is absolutely a string with a size of 1.

Square brackets can be used to get entry to factors of the string.


Example:-

Get the personality at function 1 (remember that the first persona has the role 0):

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

                            Try it Yourself»»

Looping Through a String

Since strings are arrays, we can loop via the characters in a string, with a for loop.

Example:-

        Loop thru the letters in the phrase "banana":

        for x in "banana":
        print(x)


                            Try it Yourself»»

String Length


To get the size of a string, use the len( ) function.

Example:-

        The len( ) feature returns the size of a string:

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


                            Try it Yourself»»


Check String

To test if a positive phrase or persona is current in a string, we can use the key-word in.

Example:-


        Check if "free" is existing in the following text:

        txt = "The exceptional matters in lifestyles are free!"
        print("free" in txt)


                            Try it Yourself»»

Use it in an if statement:


Example:-

        Print solely if "free" is present:

        txt = "The first-rate matters in existence are free!"
        if "free" in txt:
        print("Yes, 'free' is present.")


                          Try it Yourself»» 

Check if NOT


To test if a sure phrase or persona is NOT existing in a string, we can use the key-word
not in.

Example:-

            Check if "expensive" is NOT current in the following text:

            txt = "The quality matters in existence are free!"
            print("expensive" no longer in txt)

                            Try it Yourself»»

Use it in an if statement:


Example:-

        print solely if "expensive" is NOT present:

        txt = "The quality matters in lifestyles are free!"
        if "expensive" now not in txt:
        print("No, 'expensive' is NOT present.")

                            Try it Yourself»»

Python - Slicing Strings


Slicing


You can return a vary of characters via the usage of the slice syntax.

Specify the begin index and the quit index, separated by way of a colon, to return a section of the string.


Example:-

        Get the characters from function two to function 5 (not included):

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


                      
Try it Yourself»»
 
Note: The first persona has index 0.

Slice From the Start

By leaving out the begin index, the vary will begin at the first character:


Example:-

        Get the characters from the begin to role 5 (not included):

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


                        Try it Yourself»»

Slice To the End

By leaving out the give up index, the vary will go to the end:

Example:-

        Get the characters from role 2, and all the way to the end:

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


                        
Try it Yourself»»       
                 
Negative Indexing

Use terrible indexes to begin the slice from the cease of the string:

Example:-

        Get the characters:

        From: "o" in "World!" (position -5)

        To, but no longer included: "d" in "World!" (position -2):


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


                            Try it Yourself»»

Python - Modify Strings


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

Upper Case:

Example:-

        The upper( ) approach returns the string in higher case:

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

                          
Try it Yourself»» 

Lower Case

Example:-

        The lower( ) approach returns the string in decrease case:

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

                    
                        Try it Yourself»» 


Remove White-space


White-space is the house earlier than and/or after the genuine text, and very regularly you desire to take away this space.

Example:-

        The strip( ) approach eliminates any white-space from the opening or the end:

        a = " Hello, World! "
        print(a.strip( ))
            # returns "Hello, World!"
    
                         Try it Yourself»»

Replace String


Example:-

        The replace( ) approach replaces a string with every other string:

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


                    Try it Yourself»»

Split String


The split( ) approach returns a listing the place the textual content between the precise separator turns into the listing items.

Example:-

        The split( ) approach splits the string into sub-strings if it finds situations of the         separator:

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

                        Try it Yourself»»


Python - String Concatenation


String Concatenation

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

Example:-

        Merge variable a with variabl
e b into variable c:

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


                    Try it Yourself»»

Example:-

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

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


                    Try it Yourself»»

Python - Format - Strings


String Format


As we discovered in the Python Variables chapter, we can't mix strings and numbers like this:

Example:-

           age = 36
           txt = "My identify is John, I am " + age
           print(txt)

                        Try it Yourself»»

But we can mix strings and numbers by using the usage of the format( ) method!

The format( ) technique takes the handed arguments, codecs them, and locations them in the string the place the placeholders { } are:

Example:-

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

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

                            Try it Yourself»»

The format( ) technique takes limitless variety of arguments, and are positioned into the respective placeholders:

Example:-

        quantity = 3
        itemno = 567
        price = 49.95

        myorder = "I favor {} portions of object {} for {} dollars."
        print(myorder.format(quantity, itemno, price))


                            Try it Yourself»»

You can use index numbers {0} to be positive the arguments are positioned in the right placeholders:

Example:-

        quantity = 3
        itemno = 567
        price = 49.95
        myorder = "I desire to pay {2} bucks for {0} portions of object {1}."
        print(myorder.format(quantity, itemno, price))


                                Try it Yourself»»

Python - Escape Characters

Escape Character


To insert characters that are unlawful in a string, use an get away character.

An break out personality is a backslash
\ accompanied by way of the persona you choose to insert.

An instance of an unlawful personality is a double quote interior a string that is surrounded with the aid of double quotes:


Example:-

You will get an error if you use double rates interior a string that is surrounded by way of double quotes:

        txt = "We are the so-called "Vikings" from the north."

                            Try it Yourself»»

To restoration this problem, use the get away persona \" :

Example:-

The get away personality lets in you to use double prices when you generally would no longer be allowed:

        txt = "We are the so-called \"Vikings\" from the north."

                            Try it Yourself»»

Escape Characters


Other get away characters used in Python:

        Code                                             Result                                         Try it

            \'                                         Single Quote                                    Try it

            \\                                           Backslash                                      Try it

            \n                                         New Line                                        Try it

            \r                                     Carriage Return                                 Try it

            \t                                                 Tab                                            Try it

            \b                                         Backspace                                      Try it

            \f                                          Form Feed                                      

            \ooo                                     Octal value                                    Try it

            \xhh                                     Hex value                                      Try it





Python - String Methods


String Methods


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

Note: All string strategies returns new values. They do now not alternate the authentic string.


Method                         Description

capitalize( )          Converts the first persona to higher case.

casefold( )
            Converts string into lower case.

center( )                 Returns a founded string.

count( )                  Returns the range of instances a certain price happens in a string.

encode( )               Returns an encoded model of the string.

endswith( )           Returns actual if the string ends with the unique value.

expandtabs( )       Sets the tab dimension of the string.

find( )                     Searches the string for a certain price and returns the role of the    place it was once found.

format( )                Formats unique values in a string.

format_map( )     Formats designated values in a string.

index( )                  Searches the string for a targeted cost and returns the role of the place it used to be found.

isalnum( )             Returns True if all characters in the string are alphanumeric.

isalpha( )               Returns True if all characters in the string are in 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 decrease case.

isnumeric( )          Returns True if all characters 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 white-spaces.

istitle( )                  Returns True if the string follows the guidelines of a title.

isupper( )               Returns True if all characters in the string are higher case.

join( )                     Joins the factors of an iterable to the quit of the string.

ljust( )                    Returns a left justified model of the string.

lower( )                 Converts a string into decrease case.

lstrip( )                  Returns a left trim model of the string.

maketrans( )        Returns a translation desk to be used in translations.

partition( )            Returns a tuple the place the string is parted into three parts.

replace( )               Returns a string the place a distinctive price is changed with a exact value.

rfind( )                   Searches the string for a distinct cost and returns the closing role of the place it used to be found.

rindex( )                Searches the string for a certain cost and returns the closing role of the place it used to be found.

rjust( )                    Returns a proper justified model of the string.

rpartition( )          Returns a tuple the place the string is parted into three parts.

rsplit( )                  Splits the string at the distinctive separator, and returns a list.

rstrip( )                  Returns a proper trim model of the string.

split( )                    Splits the string at the particular separator, and returns a list.

splitlines( )
          Splits the string at line breaks and returns a list.

startswith( )         Returns genuine if the string begins with the specific value.

strip( )                    Returns a trimmed model of the string.

swapcase( )          Swaps cases, decrease case turns into top case and vice versa.

title( )                     Converts the first persona of every phrase to higher case.

translate( )           Returns a translated string.

upper( )                 Converts a string into top case.

zfill( )                     Fills the string with a distinct range of zero values at the beginning.


Post a Comment

0 Comments