Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python - Strings and Formatting

Python - Strings and Formatting

Python - Strings and Formatting

This slide introduces the strings, string manipulation and formatting in python.
This slide is a part of a the Course "Learn Python, Django & Web Development".
Read More here https://github.com/kabirbaidhya/learn-python-django-web.

Kabir Baidhya

March 18, 2017
Tweet

More Decks by Kabir Baidhya

Other Decks in Technology

Transcript

  1. What we know now A er the previous sessions we

    know about the following: 1. Variables in Python 2. Data Types 3. Operators and Expressions 4. Git ‐ a li le bit more :)
  2. String A string is tradi onally a sequence of characters.

    Strings are one of the common data types in all programming languages and python is not an excep on. String in Python is handled with s t r object and strings are immutable sequences.
  3. Strings in Python Strings can be represented in various of

    ways: # U s i n g S i n g l e Q u o t e s m y _ s t r i n g 1 = ' T h i s i s a s t r i n g ' # U s i n g D o u b l e Q u o t e s m y _ s t r i n g 2 = " T h i s i s a s t r i n g t o o " . # U s i n g T r i p l e Q u o t e s ( M u l t i l i n e s t r i n g s ) m y _ s t r i n g 3 = ' ' ' L o r e m i p s u m d o l o r s i t a m e t , c o n s e c t e t u r a d i p i s c i n s e d d o e i u s m o d t e m p o r i n c i d i d u n t u t l a b o r e e t d o l o r e m a g n a a l i q u a # Y o u c o u l d w r i t e i t w i t h d o u b l e q u o t e s a s w e l l m y _ s t r i n g 3 = " " " L o r e m i p s u m d o l o r s i t a m e t , c o n s e c t e t u r a d i p i s c i n s e d d o e i u s m o d t e m p o r i n c i d i d u n t u t l a b o r e e t d o l o r e m a g n a a l i q u a
  4. Common Opera ons The following opera ons are supported by

    strings and most of the sequences. Opera on Result x in s True if an item of s is equal to x, else False x not in s False if an item of s is equal to x, else True s + t the concatena on of s and t s * n or n * s equivalent to adding s to itself n mes s[i] ith item of s, origin 0 s[i:j] slice of s from i to j s[i:j:k] slice of s from i to j with step k
  5. Common Opera ons Opera on Result len(s) length of s

    min(s) smallest item of s max(s) largest item of s s.index(x[, i[, j]]) index of the first occurrence of x in s (at or a er index i and before index j) s.count(x) total number of occurrences of x in s
  6. Example 1 s = i n p u t (

    ' E n t e r a s t r i n g : ' ) p r i n t ( " Y o u h a v e e n t e r e d " + s ) p r i n t ( " N o . o f c h a r a c t e r s = % d " % l e n ( s ) ) p r i n t ( " F i r s t C h a r a c t e r = % s " % s [ 0 ] ) p r i n t ( " L a s t C h a r a c t e r = % s " % s [ l e n ( s ) ­ 1 ] )
  7. Example 2 s = i n p u t (

    ' E n t e r a s t r i n g : ' ) # C o u n t t h e n u m b e r o f v o w e l s p r i n t ( " N o . o f ' a ' = % s " % s . c o u n t ( ' a ' ) ) p r i n t ( " N o . o f ' e ' = % s " % s . c o u n t ( ' e ' ) ) p r i n t ( " N o . o f ' i ' = % s " % s . c o u n t ( ' i ' ) ) p r i n t ( " N o . o f ' o ' = % s " % s . c o u n t ( ' o ' ) ) p r i n t ( " N o . o f ' u ' = % s " % s . c o u n t ( ' u ' ) ) # C a l c u l a t e P e r c e n t a g e o f v o w e l s t o t a l _ v o w e l s = s . c o u n t ( ' a ' ) + s . c o u n t ( ' e ' ) + s . c o u n t ( ' i ' ) + s . p e r c e n t a g e = ( f l o a t ( t o t a l _ v o w e l s ) / l e n ( s ) ) * 1 0 0 p r i n t ( " \ n % . 2 f % % a r e v o w e l s . " % p e r c e n t a g e )
  8. String Methods Method Descrip on capitalize() Return a new string

    with its first character capitalized and the rest lowercased. endswith(suffix[, start[, end]) Check if the string ends with the given suffix. Return boolean result T r u e or F a l s e startswith(prefix[, start[, end]]) Check if the string starts with the given prefix and return boolean result T r u e or F a l s e find(sub[, start[, end]]) Return the first index in the string where substring s u b is found within s t a r t to e n d of the string. Return ‐1 if not found.
  9. String Methods Method Descrip on strip([chars]) Return a new string

    with the leading and trailing characters removed. The op onal c h a r s argument defaults to removing whitespace. swapcase() Return a new string with uppercase characters converted to lowercase and vice versa. tle() Return a new tlecased version of the string where words start with an uppercase character and other le ers are lowercased. upper() Return a new uppercased version of the string.
  10. String Methods Method Descrip on lower() Return a new lowercased

    version of the string. split(sep=None, maxsplit=‐1) Splits the string into substring using the s e p argument as the separator. Return the list of spli ed substrings. format(*args, **kwargs) Perform a string forma ng opera on and return the forma ed string. replace(old, new[, count]) Return a new string by replacing all occurrences of substring o l d with n e w. If c o u n t argument is provided, only c o u n t number of replacements would be done.
  11. Example 3 t e x t = i n p

    u t ( ' E n t e r a s t r i n g : ' ) p r i n t ( " c a p i t a l i z e ( ) = " , t e x t . c a p i t a l i z e ( ) ) p r i n t ( " s t r i p ( ) = " , t e x t . s t r i p ( ) ) p r i n t ( " s w a p c a s e ( ) = " , t e x t . s w a p c a s e ( ) ) p r i n t ( " t i t l e ( ) = " , t e x t . t i t l e ( ) ) p r i n t ( " u p p e r ( ) = " , t e x t . u p p e r ( ) ) p r i n t ( " l o w e r ( ) = " , t e x t . l o w e r ( ) ) p r i n t ( " r e p l a c e ( ' a ' , ' b ' ) = " , t e x t . r e p l a c e ( ' a ' , ' b ' ) ) p r i n t ( " e n d s w i t h ( ' f o o ' ) = " , t e x t . e n d s w i t h ( ' f o o ' ) ) p r i n t ( " s t a r t s w i t h ( ' b a r ' ) = " , t e x t . s t a r t s w i t h ( ' b a r ' ) ) p r i n t ( " f i n d ( ' f o o ' ) = " , t e x t . f i n d ( ' f o o ' ) ) p r i n t ( " s p l i t ( ' ' ) = " , t e x t . s p l i t ( ' ' ) )
  12. C‐Style forma ng You probably remember the p r i

    n t f func on if you've programmed in C. You can do similar string forma ng in Python as well. You would do something like this. p r i n t ( " H e l l o % s ! " % n a m e )
  13. Example 4 # A s k t h e u

    s e r t o e n t e r f i r s t a n d l a s t n a m e . f i r s t _ n a m e = i n p u t ( ' Y o u r f i r s t n a m e : ' ) l a s t _ n a m e = i n p u t ( ' Y o u r l a s t n a m e : ' ) p r i n t ( " \ n H i % s % s ! " % ( f i r s t _ n a m e , l a s t _ n a m e ) ) p r i n t ( " I t ' s n i c e t o m e e t y o u . " )
  14. Example 5 # A s k t h e u

    s e r t o e n t e r f i r s t a n d l a s t n a m e . P I = 3 . 1 4 1 5 r a d i u s = i n p u t ( ' E n t e r r a d i u s o f c i r c l e ( m e t e r s ) : ' ) a r e a = P I * f l o a t ( r a d i u s ) * * 2 p r i n t ( " \ n A r e a o f c i r c l e = % . 2 f s q . m e t r e s " % a r e a )
  15. Format specifiers Following are the supported conversion types. Conversion Meaning

    'd' Signed integer decimal. 'i' Signed integer decimal. 'o' Signed octal value. 'u' Obsolete type – it is iden cal to 'd'. 'x' Signed hexadecimal (lowercase). 'X' Signed hexadecimal (uppercase). 'e' Floa ng point exponen al format (lowercase). 'E' Floa ng point exponen al format (uppercase).
  16. Format specifiers Conversion Meaning 'f' Floa ng point decimal format.

    'F' Floa ng point decimal format. 'g' Floa ng point format. Uses lowercase exponen al format if exponent is less than ‐4 or not less than precision, decimal format otherwise. 'G' Floa ng point format. Uses uppercase exponen al format if exponent is less than ‐4 or not less than precision, decimal format otherwise. 'c' Single character (accepts integer or single character string).
  17. Format specifiers Conversion Meaning 'r' String (converts any Python object

    using repr()). 's' String (converts any Python object using str()). 'a' String (converts any Python object using ascii()). '%' No argument is converted, results in a '%' character in the result. For in‐depth informa on about the C‐style forma ng check the official docs.
  18. New style forma ng Python provides another way for forma

    ng as well. That is using s t r . f o r m a t ( ) method. Something like this: p r i n t ( " H e l l o { } ! " . f o r m a t ( n a m e ) ) Pre y much the same, right?
  19. Example 6 Okay, check this example on what difference this

    new syntax makes. f i r s t _ n a m e = i n p u t ( ' Y o u r f i r s t n a m e : ' ) l a s t _ n a m e = i n p u t ( ' Y o u r l a s t n a m e : ' ) # O l d s t y l e f o r m a t t i n g . p r i n t ( ' H e l l o % s % s ! ' % ( f i r s t _ n a m e , l a s t _ n a m e ) ) # N e w S t y l e f o r m a t t i n g p r i n t ( ' H e l l o { } { } ! ' . f o r m a t ( f i r s t _ n a m e , l a s t _ n a m e ) ) p r i n t ( ' H e l l o { 0 } { 1 } ! ' . f o r m a t ( f i r s t _ n a m e , l a s t _ n a m e ) ) # T h i s i s w h e r e , y o u w i l l f e e l t h e d i f f e r e n c e . p r i n t ( ' H e l l o { 1 } { 0 } ! ' . f o r m a t ( f i r s t _ n a m e , l a s t _ n a m e ) ) p r i n t ( ' H e l l o { 0 } { 0 } { 1 } ! ' . f o r m a t ( f i r s t _ n a m e , l a s t _ n a m e ) )
  20. Example 7 It supports all the format specififiers you've used

    in C‐Style style forma ng. Check this. a m o u n t = i n p u t ( ' E n t e r a m o u n t i n U S D : ' ) r a t e = 1 0 0 . 0 0 a m o u n t _ n p r = f l o a t ( a m o u n t ) * r a t e p r i n t ( ' E q u i v a l e n t a m o u n t : N P R . { : . 2 f } ' . f o r m a t ( a m o u n t _ n p r ) )
  21. Exercise 1 Write a program to ask for the marks

    of 5 different subjects and print the total marks obtained and the total percentage.
  22. Exercise 2 Write a program to ask for the equa

    on of a line in the form y = m x + c. And print the values of slope and y‐ intercept of the line. (Hint: Use s p l i t ( ).)
  23. Exercise 3 Write a program to ask for the user's

    date of birth in Y Y Y Y ­ M M ­ D D format and calculate the user's age. (Hint: Use s p l i t ( ) method.)