Posts

Showing posts from May, 2023

Python String zfill() Method

The Python zfill() method is used to return a string where zeros (0) are added at the beginning of the string until it reaches a specified length. It returns a new string with the zero-filled version of the original string. For example: text = "Hello world" result = text.zfill(15) print(result) # Output: 00000Hello world You can also use zfill() on a string that contains numbers or symbols. The zfill() method does not affect them and only adds zeros before them. For example: text = "10.00" result = text.zfill(8) print(result) # Output: 00010.00 If you have any questions about this code, you can drop a line in comment .

Python String translate() Method

The Python translate() method is used to return a string where each character is mapped to its corresponding character as per a translation table. It returns a new string with the translated characters. To use translate() , you need to first create a translation table using the maketrans() method. The maketrans() method takes two parameters: a string of characters that need to be replaced, and a string of characters that will replace them. For example: text = "Hello Sam!" # create a translation table that replaces "S" with "P" table = text.maketrans("S", "P") # apply the translation table on the text result = text.translate(table) print(result) # Output: Hello Pam! You can also use translate() to delete certain characters from a string by passing a third parameter to the maketrans() method. The third parameter is a string of characters that will be removed from the original string. For example: text = "Hello Sam!" # crea...

Python String upper() Method

The Python upper() method is used to return a string where all characters are in upper case. It returns a new string with the upper cased version of the original string. For example: text = "Hello my friends" result = text.upper() print(result) # Output: HELLO MY FRIENDS You can also use upper() on a string that contains numbers or symbols. The upper() method ignores them and only converts the alphabetic characters to upper case. For example: text = "heLLo wORld 123 !@#" result = text.upper() print(result) # Output: HELLO WORLD 123 !@# If you have any questions about this code, you can drop a line in comment .  

Python String title() Method

The Python title() method is used to return a string where the first character in every word is upper case, and the remaining characters are lower case. It returns a new string with the title cased version of the original string. For example: text = "hello world" result = text.title() print(result) # Output: Hello World You can also use title() on a string that contains numbers or symbols. The first letter after any number or symbol will be converted to upper case. For example: text = "234 k3l2 *43 fun" result = text.title() print(result) # Output: 234 K3L2 *43 Fun If you have any questions about this code, you can drop a line in comment .

Python String swapcase() Method

The Python swapcase() method is used to convert all uppercase characters to lowercase and vice versa of a given string. It returns a new string with the cases swapped. For example: text = "Hello World" result = text.swapcase() print(result) # Output: hELLO wORLD You can also use swapcase() on a string that contains a mix of upper and lower case characters. All cases will be reversed when swapcase() method is called. For example: text = "HeLLo WoRld" result = text.swapcase() print(result) # Output: hEllO wOrLD If you have any questions about this code, you can drop a line in comment .

Python String strip() Method

The Python strip() method is used to remove any leading and trailing characters from a string. By default, it removes whitespace characters (such as space, tab, newline) from both ends of the string. For example: text = "  Hello world!  " result = text.strip() print(result) # Output: Hello world! You can also pass an optional parameter characters to the strip() method. It specifies a set of characters that you want to remove from both ends of the string. For example: text = ",,,,,rrttgg.....banana....rrr" result = text.strip(",.grt") print(result) # Output: banana  If you have any questions about this code, you can drop a line in comment .

Python String startswith() Method

The Python startswith() method is used to check if a string starts with a specified value. It returns True if the string starts with the value, otherwise False. For example: text = "Hello, welcome to my world." result = text.startswith("Hello") print(result) # Output: True You can also pass optional parameters start and end to the startswith() method. They specify the start and end positions of the string where the check is performed. For example: text = "Hello, welcome to my world." result = text.startswith("wel", 7, 20) print(result) # Output: True If you have any questions about this code, you can drop a line in comment .

Python String splitlines() Method

The Python splitlines() method is used to break a string at line boundaries, such as \n (newline), \r (carriage return), \r\n (carriage return + newline) and others. It returns a list of the split strings. For example: sentence = "This is a\nmulti-line\nstring." result = sentence.splitlines() print(result) # Output: ['This is a', 'multi-line', 'string.'] You can also pass an optional parameter keeplinebreaks to the splitlines() method. If it is True, then the line breaks are preserved as part of the split strings. For example: sentence = "This is another\r\nmulti-line\r\nstring." result = sentence.splitlines(True) print(result) # Output: ['This is another\r\n', 'multi-line\r\n', 'string.'] If you have any questions about this code, you can drop a line in comment .

Python String split() Method

The Python split() method is a string method that splits a string into a list of substrings, using a specified separator as the delimiter. It has the following syntax: string.split(separator, maxsplit) where separator is an optional parameter that specifies the string to split on (default is any whitespace), maxsplit is an optional parameter that specifies how many splits to do from the left (default is -1, which means all possible splits). The split() method returns a list of substrings after splitting the string. Here are some examples of using the Python split() method: # Example 1: Split a string by space mystr = 'welcome to the jungle' result = mystr.split() print(result) # Output: ['welcome', 'to', 'the', 'jungle'] # Example 2: Split a string by comma and space mystr = 'hello, my name is Peter, I am 26 years old' result = mystr.split(', ') print(result) # Output: ['hello', 'my name is Peter', 'I am 26 ...

Python String rstrip() Method

The Python rstrip() method is a string method that removes any trailing characters (characters at the end of a string) from a string. It has the following syntax: string.rstrip(characters) where characters is an optional parameter that specifies a set of characters to be removed (default is any whitespace). The rstrip() method returns a copy of the string with trailing characters removed. Here are some examples of using the Python rstrip() method: # Example 1: Remove trailing whitespace mystr = 'Hello World   ' result = mystr.rstrip() print(result) # Output: 'Hello World' # Example 2: Remove trailing commas and periods mystr = 'apple,banana,cherry,,,,.' result = mystr.rstrip(',.') print(result) # Output: 'apple,banana,cherry' # Example 3: Remove trailing '#' mystr = 'Java and C#' result = mystr.rstrip('#') print(result) # Output: 'Java and C' If you have any questions about this code, you can drop a line in com...

Python String rsplit() Method

The Python rsplit() method is a string method that splits a string into a list of substrings, starting from the right end of the string and using a specified separator as the delimiter. It has the following syntax: string.rsplit(separator, maxsplit) where separator is an optional parameter that specifies the string to split on (default is any whitespace), maxsplit is an optional parameter that specifies how many splits to do from the right (default is -1, which means all possible splits). The rsplit() method returns a list of substrings after splitting the string. Here are some examples of using the Python rsplit() method: # Example 1: Split a string by comma mystr = 'apple,banana,cherry' result = mystr.rsplit(',') print(result) # Output: ['apple', 'banana', 'cherry'] # Example 2: Split a string by space with maxsplit=2 mystr = 'This is a sample sentence' result = mystr.rsplit(' ', 2) print(result) # Output: ['This is a...

Python String rpartition() Method

The Python rpartition() method is a string method that splits a string at the last occurrence of a specified separator and returns a tuple containing three elements: the part before the separator, the separator itself, and the part after the separator. It has the following syntax: string.rpartition(separator) where separator is a string that specifies where to split the string. If separator is found in the string, rpartition() returns a tuple with three elements. If separator is not found in the string, rpartition() returns a tuple with two empty strings and the original string. Here are some examples of using the Python rpartition() method: # Example 1: Split a string at 'and' mystr = 'Do it now and keep it simple' result = mystr.rpartition('and') print(result) # Output: ('Do it now ', 'and', ' keep it simple') # Example 2: Split a string at '-' mystr = '2021-03-06' result = mystr.rpartition('-') print(result)...

Python String rjust() Method

The Python rjust() method is a string method that right aligns a string by padding it with a specified character (space by default) to a given width. It has the following syntax: string.rjust(width, fillchar) where width is the length of the resulting string, fillchar is an optional parameter that specifies the character to fill the padding (default is space). The rjust() method returns a new string that is right justified with the given width and fillchar. Here are some examples of using the Python rjust() method: # Example 1: Right justify a string with spaces mystr = 'Hello' result = mystr.rjust(10) print(result) # Output: '     Hello' # Example 2: Right justify a string with dashes mystr = 'World' result = mystr.rjust(10, '-') print(result) # Output: '-----World' # Example 3: Right justify a number with zeros num = 42 result = str(num).rjust(5, '0') print(result) # Output: '00042' If you have any questions about this code, ...

Python String rindex() Method

The Python rindex() method is a string method that finds the last occurrence of a specified value in a string. It has the following syntax: string.rindex(value, start, end) where value is the substring to be searched for, start and end are optional parameters that specify the range of indexes to search within (default is the whole string). The rindex() method returns an integer value that represents the highest index where value is found. If value is not found, it raises a ValueError exception. Here are some examples of using the Python rindex() method: # Example 1: Find the last occurrence of 'l' in 'Hello World' greet = 'Hello World' index = greet.rindex('l') print(index) # Output: 9 # Example 2: Find the last occurrence of 'tutorials' in a sentence mystr = 'tutorialsteacher is a free tutorials website' index = mystr.rindex('tutorials') print(index) # Output: 25 # Example 3: Find the last occurrence of 'o' between ind...

Python String rfind() Method

The Python rfind() method is a string method that finds the last occurrence of a specified value in a string. It has the following syntax: string.rfind(value, start, end) where value is the substring to be searched for, start and end are optional parameters that specify the range of indexes to search within (default is the whole string). The rfind() method returns an integer value that represents the highest index where value is found. If value is not found, it returns -1. Here are some examples of using the Python rfind() method: # Example 1: Find the last occurrence of 'l' in 'Hello World' greet = 'Hello World' index = greet.rfind('l') print(index) # Output: 9 # Example 2: Find the last occurrence of 'tutorials' in a sentence mystr = 'tutorialsteacher is a free tutorials website' index = mystr.rfind('tutorials') print(index) # Output: 25 # Example 3: Find the last occurrence of 'o' between index 0 and 5 greet = 'H...

Python String replace() Method

The Python replace() method is a string method that replaces a specified phrase with another specified phrase. It has the following syntax: string.replace(oldvalue, newvalue, count) where oldvalue is the substring to be replaced, newvalue is the new substring that will replace it, and count is an optional parameter that specifies how many occurrences of oldvalue to replace (default is all occurrences). Here are some examples of using the Python replace() method: # Example 1: Replace all occurrences of 'lemons' with 'oranges' mystr = 'lemons, bananas, lemons, apples, cherries' newstr = mystr.replace('lemons', 'oranges') print(newstr) # Output: oranges, bananas, oranges, apples, cherries # Example 2: Replace only one occurrence of 'apples' with 'pears' mystr = 'lemons, bananas, lemons, apples, cherries' newstr = mystr.replace('apples', 'pears', 1) print(newstr) # Output: lemons, bananas, lemons, pears cherr...

Python String partition() Method

The partition() method is a string method that splits the string at the first occurrence of a given separator and returns a tuple containing three elements: the part before the separator, the separator itself, and the part after the separator. If the separator is not found in the string, then the tuple will contain the original string and two empty strings. Here are some examples of using the partition() method: # example 1: split a string by a word txt = "I could eat bananas all day" x = txt.partition("bananas") print(x) # ('I could eat ', 'bananas', ' all day') # example 2: split a string by a symbol txt = "#1 Harbor Side" x = txt.partition("1") print(x) # ('#', '1', ' Harbor Side') # example 3: split a string by an empty separator txt = "Hello World" x = txt.partition("") print(x) # ValueError: empty separator # example 4: split a string by a non-existing separator txt = ...

Python String maketrans() Method

The maketrans() method is a string method that returns a mapping table that can be used with the translate() method to replace specified characters. The maketrans() method can take one or two arguments. If one argument is given, it must be a dictionary mapping characters to characters. If two arguments are given, they must be strings of equal length, and each character in the first string will be mapped to the corresponding character in the second string. Optionally, a third argument can be given as a string of characters that will be removed from the original string. Here are some examples of using the maketrans() method: # example 1: create a mapping table using a dictionary txt = "Hello Sam!" mydict = {"H": "J", "S": "P"} mytable = str.maketrans(mydict) print(txt.translate(mytable)) # Jello Pam! # example 2: create a mapping table using two strings txt = "Hi Sam!" x = "mSa" y = "eJo" mytable = str.m...

Python String lstrip() Method

The lstrip() method is a string method that returns a copy of the string with leading characters removed. The leading characters are the ones at the beginning of the string. By default, it removes any whitespace characters, but you can also specify a set of characters to be removed as an argument. Here are some examples of using the lstrip() method: # example 1: remove leading whitespace characters string = "   Hello World   " print(string.lstrip()) # Hello World # example 2: remove leading specific characters string = ",,,,,ssaaww.....banana" print(string.lstrip(",.asw")) # banana # example 3: remove leading specific characters in any order string = "#$2Hello World#$2" print(string.lstrip("$2#")) # Hello World#$2 If you have any questions about this code, you can drop a line in comment .

Python String lower() Method

The lower() method is a string method that returns a new string with all uppercase characters converted to lowercase. It does not affect any lowercase characters or non-alphabetical characters. Here are some examples of using the lower() method: # example 1: convert a string to lowercase string = "HELLO this IS Btechgeeks" print(string.lower()) # hello this is btechgeeks # example 2: convert a string with numbers and symbols to lowercase string = "GooD MORNING btechgeeks@123 $$#" print(string.lower()) # good morning btechgeeks@123 $$# # example 3: convert a string that is already lowercase string = "i am a string!" print(string.lower()) # i am a string! If you have any questions about this code, you can drop a line in comment .

Python String isidentifier() Method

The Python isidentifier() method is a string method that returns True if the string is a valid identifier, otherwise False. A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces. Identifiers are used to name variables, functions, classes, modules, etc. in Python. Here are some examples of using the isidentifier() method: # Example 1: A simple example of identifier testing using isidentifier() method[^3^][1] # Variable declaration str = 'abcdef' # Calling function if str.isidentifier() == True:     print("It is an identifier") else:     print("It is not identifier") # Output: It is an identifier # Example 2: The isidentifier() method will return False if the string contains spaces or starts with a number[^1^][2] [^4^][4] print('Py thon'.isidentifier()) print('22Python'.isidentifier()) # Output: False # Output...

Python String isdigit() Method

The Python isdigit() method is a string method that returns True if all the characters in a string are digits, otherwise False. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. The method does not support floats. Here are some examples of using the isdigit() method: # Example 1: A simple example of digit testing using isdigit() method[^4^][1] # Variable declaration str = '12345' # Calling function str2 = str.isdigit() # Displaying result print(str2) # Output: True # Example 2: The isdigit() method will return False if the string contains whitespaces, symbols, or alphabets[^3^][4] print('$100'.isdigit()) print('100 '.isdigit()) # Output: False # Output: False # Example 3: Superscript and subscripts (usually written using Unicode) are also considered digit characters[^3^][4] print('\u00B2'.isdigit()) print('\u2082'.isdigit()) print('²5'.isdigit()) # Output: True # Out...

Python String ljust() Method

The ljust() method is a string method that returns a left-justified string within a given minimum width. If a fill character is specified, it also fills the remaining space with that character. If the width is less than or equal to the length of the string, it returns the original string. Here are some examples of using the ljust() method: # example 1: left justify a string with spaces string = "cat" width = 5 print(string.ljust(width)) # cat # example 2: left justify a string with dashes string = "Hi" width = 4 print(string.ljust(width, "-")) # Hi-- # example 3: left justify a string with no change string = "banana" width = 3 print(string.ljust(width)) # banana If you have any questions about this code, you can drop a line in comment .  

Python String join() Method

The join() method is a string method that takes an iterable object (such as a list, tuple, string, set, or dictionary) and returns a string that is the concatenation of the elements of the iterable, separated by the string on which it is called. Here are some examples of using the join() method: # example 1: join a list of strings with a comma sep = ',' names = ['Steve', 'Bill', 'Ravi', 'Jonathan'] print(sep.join(names)) # Steve,Bill,Ravi,Jonathan # example 2: join a string with a comma mystr = 'Hello' print(sep.join(mystr)) # H,e,l,l,o # example 3: join a tuple of strings with a comma nums = ('1', '2', '3', '4') print(sep.join(nums)) # 1,2,3,4 # example 4: join a set of strings with a comma langs = {'Python', 'C#', 'Java', 'C++'} print(sep.join(langs)) # Python,C#,Java,C++ If you have any questions about this code, you can drop a line in comment .

Python String isupper() Method

The isupper() method is a string method that returns True if all the characters in a string are uppercase, otherwise False. It also returns False if the string contains no alphabets. Here are some examples of using the isupper() method: # example 1: check if a string is all uppercase string = "HELLO WORLD" print(string.isupper()) # True # example 2: check if a string with symbols and numbers is all uppercase string = "PYTHON IS #1" print(string.isupper()) # True # example 3: check if a string with lowercase characters is all uppercase string = "Hello World" print(string.isupper()) # False # example 4: check if a string with no alphabets is all uppercase string = "#1?><~ ()+=*-+./\\ []" print(string.isupper()) # False If you have any questions about this code, you can drop a line in comment .

Python String istitle() Method

The Python istitle() method is a string method that returns True if all words in a string start with an uppercase letter and the rest of the word are lowercase letters, otherwise False. Symbols and numbers are ignored. Here are some examples of using the istitle() method: # Example 1: A simple example of title testing using istitle() method[^2^][6] s = 'Python Is Good.' print(s.istitle()) # Prints True s = 'Python is good' print(s.istitle()) # Prints False s = 'This Is @ Symbol.' print(s.istitle()) # Prints True s = '99 Is A Number' print(s.istitle()) # Prints True s = 'PYTHON' print(s.istitle()) # Prints False # Example 2: The istitle() method can be used with the title() method to check a string before converting it to a titlecased string[^3^][3] ustr=input("Enter a string: ") if not ustr.istitle():     ustr = ustr.title()     print('Converted to TitleCase:', ustr) else:     print('You entered a TitleCase string') If...

Python String isspace() Method

The Python isspace() method is a string method that returns True if all the characters in a string are whitespace characters, otherwise False. Whitespace characters are characters that are used for spacing, such as tabs (\t), spaces ( ), newlines (\n), etc. Here are some examples of using the isspace() method: # Example 1: A simple example of whitespace testing using isspace() method[^3^][4] mystr = ' ' print(mystr.isspace()) # Prints True mystr = '\t' print(mystr.isspace()) # Prints True mystr = 'tt' print(mystr.isspace()) # Prints False mystr = '\n\r' print(mystr.isspace()) # Prints True # Example 2: The isspace() method will return False even if one character is not a whitespace[^3^][4] mystr = 'Hello World' print(mystr.isspace()) # Prints False mystr = ' Hello ' print(mystr.isspace()) # Prints False If you have any questions about this code, you can drop a line in comment .

Python String isprintable() Method

The Python isprintable() method is a string method that returns True if all the characters in a string are printable, otherwise False. A printable character is one that occupies some space on the screen. Examples of non-printable characters are carriage return (\r) and line feed (\n). Here are some examples of using the isprintable() method: # Example 1: A simple example of printable testing using isprintable() method[^3^][1] Given_string = 'Welcome to Python-programs' Given_string = 'hello this is\n btechgeeks' Given_string = ' ' print(Given_string.isprintable()) # Prints True # Prints False # Prints True # Example 2: The isprintable() method will return True if the string contains ASCII characters[^2^][2] mystr = '12345' print(mystr.isprintable()) # Prints True mystr = '#1 Harbour Side' print(mystr.isprintable()) # Prints True mystr = '\t' # tab character print(mystr.isprintable()) # Prints False If you have any questions about this ...

Python String isnumeric() Method

The Python isnumeric() method is a string method that returns True if all the characters in a string are numeric (0-9), otherwise False. The method also considers exponents such as 3² and ¾ as numeric values. Here are some examples of using the isnumeric() method: # Example 1: A simple example of numeric testing using isnumeric() method[^3^][2] str1 = "HumptyDumpty" str2 = "314" print(str1.isnumeric()) print(str2.isnumeric()) # Prints False # Prints True # Example 2: The isnumeric() method will return True if the string contains unicode numeric characters[^4^][3] [^5^][6] numstr = 'u0034' # u0034 is 4 print(numstr.isnumeric()) # Prints True numstr = 'u00BD' # u00BD is ½ print(numstr.isnumeric()) # Prints True numstr = '¾' print(numstr.isnumeric()) # Prints True # Example 3: The isnumeric() method will return False if the string contains any non-numeric character[^1^][5] txt = "565543a" x = txt.isnumeric() print(x) # Prints False I...

Python String islower() Method

The Python islower() method is a string method that returns True if all alphabets in a string are lowercase alphabets and there is at least one alphabet, otherwise False. The method does not check for symbols or numbers. Here are some examples of using the islower() method: # Example 1: A simple example of lowercase testing using islower() method[^3^][1] # Check if all characters in the string are lowercase S = 'abcd' x = S.islower() print(x) # Prints True # Example 2: The islower() method will return False if the string contains any uppercase alphabet[^1^][2] [^4^][4] txt = "Hello world!" x = txt.islower() print(x) # Prints False # Example 3: The islower() method will return False if the string contains only symbols or numbers but not alphabets[^2^][3] mystr='#1?><~ ()+=*-+./\\ []' print(mystr.islower()) # Prints False If you have any questions about this code, you can drop a line in comment .

Python String isdecimal() Method

The isdecimal() method is a string method that returns True if all the characters in the string are decimal characters (0-9). For example: num = "123" print(num.isdecimal()) # prints True The method returns False if the string contains any non-decimal characters, such as letters, spaces, punctuation marks, symbols, etc. For example: num = "12.3" print(num.isdecimal()) # prints False If you have any questions about this code, you can drop a line in comment .