Python object class
- Every object in python is derived from the class object
- Writing the class in the below fashion
class Dummy:
pass
is equal to
class Dummy(object):
pass
- Now if we create an object, we can access methods of class object
class Dummy:
pass
d = Dummy()
d.__str__()
- In the above __ str() __is method defined in object class
Strings in python
- You can create a python string by enclosing sequence of character in single or double quotes
- Strings in python3 are unicode
- Launch python shell
# in both the cases type will be str
course = "python"
type(course)
course = 'python'
type(course)
- Refer Here
- Single quotes can be used to enclose double quoted messages/text and vice versa
- There are some special strings is in python
- f-string: They are used for formatting
name = "Python" print(f"name is {name} ")
- raw strings: The start with r or R
- unicode string: This is default string
- bytes
- Multiline string: Will have triple quotes
message = ''' Hello how are you doing This is a special message to you Wish you a good luck ''' print(message)
- Empty strings in python:
- Creating a string with str()
- Escape Sequences
- \n
- \t
- \
- "
String Operations
- Combine strings using +
- Duplicate strings with *
- Get a character at a specific position using []
- replace strings with replace() method
- Getting substrings with slicing operators
- [:] extracts the entire sequence from start to end
- [start:] specifies to extract from start offset to end
- [:end] specifies to extract from start to end offset minus 1
- [start:end]
- [start:end:step]
- Get length using len()
- Splitting strings with split()
- Some other operations
- Casing methods
- capitalize()
- title()
- upper()
- lower()
- swapcase()
String formatting
- For formatting strings in python there are three ways
- old style
- new style
- f-strings
Old Style string formatting
- This formatting uses conversion types
- %s: string
- %d: decimal integer
- %x: hex integer
- %o: octal integer
- %f: float
- %e: exponential
- %%: a literal %
movie = "Avengers"
character_liked = "ironman"
rating = 5
"I have watched %s and i liked %s character in the movie. I would like to %d as rating" % (movie, character_liked, rating)