Basics of Python Strings.
- A Python string is a sequence, which consists of zero or more characters.
- The string is an immutable data structure, which means they cannot be changed.
String Function
- Len function: In order to find the length of the string. Ex len(string variable).
- The subscript operator([]):It is used to access the elements of string, list tuple, and so on.
Syntax: <given string>[index].
- The -1 index represents the last character
Slicing for substrings
- In many situations, you might need a particular portion of strings such as the first three characters of the string.
- Python’s subscript operator uses slicing.
- In slicing, colon : is used. An integer value will appear on either side of the colon.
- print(name[0:4])
print(name[23])
print(name[0:-1])
print(name[:8])
print(name[::2])
Python string methods:
- Count Function:The count method returns the number of occurrences of the substring substr in string
- Find Method: The find() method is used to find out whether a string occurs in a given string or its substrings.
- find method will only give the index of the first occurrence.
- If you want to find the occurrence from right, you can use the rfind method.
String case methods
- lower() method.
- upper() method
- capitalize() method:capitalize the first character of the line.
- Title method: convert the first character of every word of the string in uppercase.
- A swapcase method allows the user to swap the cases:
String strip methods
- Dealing with the strings, many times programmers encounter the problem of undesirable character/characters at the end or beginning of the string, such as space or new line character at the end, for example, ” Baba saheb ” and “Dr Ambedkar n”.
- To handle these problems, the Python string class comes loaded with three methods.
- Rstrip method:unwanted character/characters get removed from the r
- If you do not provide any chars as argument, then space is taken as default. right side of the string.
- If you want to strip from the left-side use the lstrip() method. If you want to strip from both sides, use the strip() method.
String split methods
- Sometimes we see strings in the form of parts.
- based upon delimiters, we can split strings into parts and take the desirable part.
Syntax :Str1.split(“delimiter”, num)
- The split method returns a list of all the words of the string separated by a delimiter and the num integer specifies the maximum splits.
- If you don’t provide any delimiter, then the space is taken as the default.
- If you want that splits should be started from the right, then you can use the rsplit()
Some special methods of string
- Replace : This method returns a copy of the string in which the old character(s) are replaced with new character(s).
- Join Method : Consider you have a sequence (list or tuple) of string and you want to join values of the sequence.
String Boolean Method
- return the value in the form of True or False based upon certain conditions.
- Endswith method: Sometime we are interested in strings which are ends with particular substring. For this we use string method endswith()
- Startwith method:which works the same way as the previous method, just check the condition from the beginning.
- Isalpha method: assure that the given string must contain only letters.blank spaces are not allowed.
- isalnum() method : check the alphanumeric characters appearing in the string. This method returns True if the string contains only alphanumeric characters like hello123 allowed but hello123# is not allowed. Blank space are not allowed
- Isdigit method: If you only want to check digits, then you can use the isdigit() method
- isspace(), which returns True if the string contains only spaces
- The istitle() method returns True if the string is in title case.
- Islower()- Check Lower Case
- IsUpper()- Check Upper Case
- Min():The min() function returns the min character from string str1 according to the ASCII value.
- Max():which returns the max characters from string str according to the ASCII value
All Example:
"""import ctypes name = 'yogesh sharma' # Store Address nameaddress = id(name) # Print Address print(id(name)) # Update String name = 'vikas sharma' # memory address will be changed print(id(name)) # Get Value of Memory Address name2 = ctypes.cast(nameaddress,ctypes.py_object).value print(name2)""" # Slicing Function """name = 'yogesh' print(len(name)) print(name[1]) print(name[5]) print(name[-1]) print(name[-6])""" # Slicing for substring """name ='My Name is Yogesh Sharma' print(name[0:4]) print(name[23]) print(name[0:-1]) print(name[:8]) print(name[::2])""" # String Methods """name = "My Name is Yogesh sharma" print(name.count('a')) # Search Start Index print(name.count('a',8,24)) print(name.find('Name')) # TO Find first Index from right print(name.rfind('m')) # output 3 2 3 22 """ # String Case Methods """name = 'My Name is yogesh sharma' # Lower case print(name.lower()) # Upper case print(name.upper()) # Capatalize case print(name.capitalize()) # Title method print(name.title()) # Swap case print(name.swapcase()) #Output my name is yogesh sharma MY NAME IS YOGESH SHARMA My name is yogesh sharma My Name Is Yogesh Sharma mY nAME IS YOGESH SHARMA""" # string Strip Methods """name = 'Yogesh Sharma' print(name.rstrip('rma')) # For Blank space from right side name1 = ' vikas sharma ' print(name1.rstrip()) # Strip from left side print(name1.lstrip()) # Strip from both sides print(name1.strip()) # Output Yogesh Sh vikas sharma vikas sharma vikas sharma """ # String split methods. Returns output in a list mydate = '12-01-2007' print(mydate.split('-',1)) # ['12', '01-2007'] print(mydate.split('-')) # ['12', '01', '2007'] # get Value of list newdatelist = mydate.split('-') print(newdatelist[1]) # 01 # Without Deliminator name2 = 'my name is yogesh sharma' print(name2.split()) # ['my', 'name', 'is', 'yogesh', 'sharma'] # Rsplit Example print(mydate.rsplit('-',1)) # ['12-01', '2007'] # replace method name3 = 'Yogesh Sharma was a nice person' print(name3.replace('was','is')) #Yogesh Sharma is a nice person # Maximum Replacements name4 = 'Yogesh sharma was a nice person, his reputation was gud' print(name4.replace('was','is',1)) # Yogesh sharma is a nice person, his reputation was gud # Join Method Example mylist=['yogesh','sharma'] print(''.join(mylist)) # Output - yogeshsharma print('-'.join(mylist)) # Output - yogesh-sharma print(' '.join(mylist)) # Output- yogesh sharma # String Boolean Methods # endswith method example - return True or false value only name4 = 'My name is Yogesh sharma' print(name4.endswith('rma')) # Output - True print(name4.endswith('pma')) # Output - False # To check upto particular Index Only str1 = "Life should be great rather than long" print(str1.endswith('er',0,27)) # output - True # Startwith method print(str1.startswith('Li')) print(str1.isalpha()) # Output: False (Blank space are not allowed) str2 = 'YogeshSharma' print(str2.isalpha()) # Output = True str3 = 'hello 123' print(str3.isalnum()) #output -True # isdigit method str4 = '123' print(str4.isdigit()) # Output = True # isspace method str5 = "hello " print(str5.isspace()) #Output- False str6 = ' ' print(str6.isspace()) # Output - True #istitle method str7 = 'My Name Is Yogesh Sharma' print(str7.istitle()) # Output- True # islower and isupper methods print(str7.islower()) print(str7.isupper())