String Built-in Function in Python

Admin
By -
14 minute read
1

Python String Methods:

    Python has a set of built-in methods that you can use on strings.There are totally 45 methods till date...
  • capitalize()
  • casefold()
  • center()
  • count()
  • encode()
  • endswith()
  • expandtabs()
  • find()
  • format()
  • format_map()
  • index()
  • isalnum()
  • isalpha()
  • isascii()
  • isdecimal()
  • isdigit()
  • isidentifier()
  • islower()
  • isnumeric()
  • isprintable()
  • isspace()
  • istitle()
  • isupper()
  • join()
  • ljust()
  • lower()
  • lstrip()
  • maketrans()
  • partition()
  • removeprefix()
  • removesuffix()
  • replace()
  • rfind()
  • rindex()
  • rjust()
  • rpartition()
  • rsplit()
  • rstrip()
  • split()
  • splitlines()
  • startswith()
  • strip()
  • swapcase()
  • title()
  • translate()
  • upper()
  • zfill()

1. str.capitalize()

    The capitalize() method returns a string where the first character is upper case, and the rest is lower case.
Syntax: ->  string.capitalize()
Coding;
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
Output:
Hello, and welcome to my world

2. casefold()

    The casefold() method returns a string where all the characters are lower case.
    
    This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case, and will find more matches when comparing two strings and both are converted using the casefold() method.

Syntax: ->    string.casefold()
Coding;
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
Output:
hello, and welcome to my world!


3. str.center()

    The center() method will center align the string, using a specified character (space is default) as the fill character.
Syntax: ->    string.center(length, character)
length The length of the returned string
character The character to fill the missing space on each side. Default is " " (space)
Coding;
txt = "banana"
x = txt.center(20)
print(x)
Output:
       banana      

4. str.count()

    The count() method returns the number of times a specified value appears in the string.
Syntax: ->    string.count(value, start, end)
value A String. The string to value to search for
start An Integer. The position to start the search. Default is 0
end An Integer. The position to end the search. Default is the end of the string
Coding;
txt = "I love apples, apple is my favorite fruit"
x = txt.count("apple")
print(x)
Output:
2

5. str.encode()

    The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
Syntax: ->    string.encode(encoding=encoding, errors=errors)   
Coding;
txt = "My name is Ståle"
x = txt.encode()
print(x)
Output:
b'My name is St\xc3\xe5le'

6. str.endswith()

    The endswith() method returns True if the string ends with the specified value, otherwise False.
Syntax: ->    string.endswith(value, start, end)
value The value to check if the string ends with
start An Integer specifying at which position to start the search
end An Integer specifying at which position to end the search
Coding;
txt = "Hello, welcome to my world."
x = txt.endswith(".")
print(x)
Output:
True

7. str.expandtabs()

    The expandtabs() method sets the tab size to the specified number of whitespaces.
Syntax: ->    string.expandtabs(tabsize)
tabsize Optional. A number specifying the tabsize. Default tabsize is 8
Coding;
txt = "H\te\tl\tl\to"
x =  txt.expandtabs(2)
print(x)
Output:
H e l l o

8. str.find()

    The find() method finds the first occurrence of the specified value.

    The find() method returns -1 if the value is not found.

    The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. (See example below)

Syntax: ->    string.find(value, start, end)

value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string

Coding;
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
Output:
7

9. str.format()

    The format() method formats the specified value(s) and insert them inside the string's placeholder.

    The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.

    The format() method returns the formatted string.

Syntax: ->    string.format(value1, value2...)

value1, value2... Required. One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The values can be of any data type.
Coding;
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
Output:
For only 49.00 dollars!

10. str.index()

    The index() method finds the first occurrence of the specified value.
    The index() method raises an exception if the value is not found.
    The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found. (See example below)

Syntax: ->    string.index(value, start, end)
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Coding;
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
Output:
7

11. str.isalnum()

    The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

    Example of characters that are not alphanumeric: (space)!#%&? etc.

Syntax: ->    string.isalnum()

Coding;

txt = "Company12"
x = txt.isalnum()
print(x)
Output:
True

12. str.isalpha()

    The isalpha() method returns True if all the characters are alphabet letters (a-z).

    Example of characters that are not alphabet letters: (space)!#%&? etc.

Syntax: ->    string.isalpha()

Coding;

txt = "CompanyX"
x = txt.isalpha()
print(x)
Output:
True

13. str.isascii()

    The isascii() method returns True if all the characters are ascii characters  (a-z).
Syntax: ->    string.isascii()
Coding;
txt = "Company123★"
x = txt.isascii()
print(x)
Output:
False

14. str.isdecimal()

    The isdecimal() method returns True if all the characters are decimals (0-9).

    This method can also be used on unicode objects. See example below.

Syntax: ->    string.isdecimal()

Coding;

txt = "1234x"
x = txt.isdecimal()
print(x)
Output:
False

15. str.isdigit()

    The isdigit() method returns True if all the characters are digits, otherwise False.

    Exponents, like ², are also considered to be a digit.

Syntax: ->    string.isdigit()

Coding;

txt = "50800"
x = txt.isdigit()
print(x)
Output:
True

16. str.isidentifier()

    The isidentifier() method 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.

Syntax: ->    string.isidentifier()

Coding;

txt = "Demo"
x = txt.isidentifier()
print(x)
Output:
True

17. str.islower()

    The islower() method returns True if all the characters are in lower case, otherwise False.

    Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax: ->    string.islower()

Coding;

txt = "hello wOrld!"
x = txt.islower()
print(x)
Output:
False

18. str.isnumeric()

    The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.

    Exponents, like ² and ¾ are also considered to be numeric values.

    "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.

Syntax: ->    string.isnumeric()

Coding;

txt = "565543"
x = txt.isnumeric()
print(x)
Output:
True

19. str.isprintable()

    The isprintable() method returns True if all the characters are printable, otherwise False.

    Example of none printable character can be carriage return and line feed.

Syntax: ->    string.isprintable()

Coding;

txt = "Hello! Are you #1?"
x = txt.isprintable()
print(x)
Output:
True

20. str.isspace()

    The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax: ->    string.isspace()
Coding;
txt = "   "
x = txt.isspace()
print(x)
Output:
True

21. str.istitle()

    The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.

    Symbols and numbers are ignored.

Syntax: ->    string.istitle()

Coding;

txt = "Hello, And Welcome To My World!"
x = txt.istitle()
print(x) 
Output:
True


22. str.isupper()

    The isupper() method returns True if all the characters are in upper case, otherwise False.

    Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax: ->    string.isupper()

Coding;

txt = "THIS IS NoW!"
x = txt.isupper()
print(x) 
Output:
False


23. str.join()

    The join() method takes all items in an iterable and joins them into one string.

    A string must be specified as the separator.

Syntax: ->    string.join(iterable)

*iterable=Any iterable object where all the returned values are strings

Coding;

myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x) 
Output:
John#Peter#Vicky


24. str.ljust()

    The ljust() method will left align the string, using a specified character (space is default) as the fill character.
Syntax: ->    string.ljust(length, character)
length Required. The length of the returned string
character Optional. A character to fill the missing space (to the right of the string). Default is " " (space).
Coding;
txt = "banana"
x = txt.ljust(20)
print(x, "is my favorite fruit.")
Output:
banana              is my favorite fruit.


25. str.lower()

    The lower() method returns a string where all characters are lower case.

    Symbols and Numbers are ignored.

Syntax: ->    string.lower()

Coding;

txt = "Hello my FRIENDS"
x = txt.lower()
print(x) 
Output:
hello my friends


26. str.lstrip()

    The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax: ->    string.lstrip(characters)
Coding;
txt = "     banana     "
x = txt.lstrip()
print("of all fruits", x, "is my favorite") 
Output:
of all fruits banana     is my favorite


27. str.maketrans()

    The maketrans() method returns a mapping table that can be used with the translate() method to replace specified characters.
Syntax: ->    str.maketrans(x, y, z)
x Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace.
y Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string.
z Optional. A string describing which characters to remove from the original string.
Coding;
txt = "Hello Sam!"
mytable = str.maketrans("S", "P")
print(txt.translate(mytable))
Output:
Hello Pam!


28. str.partition()

    The partition() method searches for a specified string, and splits the string into a tuple containing three elements.

    The first element contains the part before the specified string.

    The second element contains the specified string.

    The third element contains the part after the string.

Syntax: ->    string.partition(value to search for)

Coding;

txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x) 
Output:
('I could eat ', 'bananas', ' all day')


29. str.replace()

    The replace() method replaces a specified phrase with another specified phrase.
Syntax: ->    string.replace(oldvalue, newvalue, count)
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences
Coding;
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x) 
Output:
I like apples


30. str.rfind()

    The rfind() method finds the last occurrence of the specified value.

    The rfind() method returns -1 if the value is not found.

    The rfind() method is almost the same as the rindex() method. See example below.    

Syntax: >    string.rfind(value, start, end)

value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Coding;
txt = "Mi casa, su casa."
x = txt.rfind("casa")
print(x) 
Output:
12


31. str.rindex()

    The rindex() method finds the last occurrence of the specified value.

    The rindex() method raises an exception if the value is not found.

    The rindex() method is almost the same as the rfind() method. See example below.

Syntax: >    string.rindex(value, start, end)

value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Coding;
txt = "Mi casa, su casa."
x = txt.rindex("casa")
print(x) 
Output:
12


32. str.rjust()

    The rjust() method will right align the string, using a specified character (space is default) as the fill character.
Syntax: >    string.rjust(length, character)
length Required. The length of the returned string
character Optional. A character to fill the missing space (to the left of the string). Default is " " (space).
Coding;
txt = "apple"
x = txt.rjust(20)
print(x, "is my favorite fruit.") 
Output:
              apple is my favorite fruit.


33. str.rpartition()

    The rpartition() method searches for the last occurrence of a specified string, and splits the string into a tuple containing three elements.

    The first element contains the part before the specified string.

    The second element contains the specified string.

Syntax: >    string.rpartition(value)

Coding;

txt = "I could eat apples all day, bananas are my favorite fruit"
x = txt.rpartition("apples")
print(x) 
Output:
('I could eat apples all day, ', 'bananas', ' are my favorite fruit')


34. str.rsplit()

    The rsplit() method splits a string into a list, starting from the right.

    If no "max" is specified, this method will return the same as the split() method.

Syntax: >    string.rsplit(separator, maxsplit)

separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"
Coding;
txt = "apple, banana, cherry"
x = txt.rsplit(", ")
print(x) 
Output:
['apple', 'banana', 'cherry']


35. str.rstrip()

    The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
Syntax: >    string.rstrip(characters)
Coding;
txt = "     apple     "
x = txt.rstrip()
print("of all fruits", x, "is my favorite") 
Output:
of all fruits     apple is my favorite


36. str.split()

    The split() method splits a string into a list.

    You can specify the separator, default separator is any whitespace.

Syntax: >    string.split(separator, maxsplit)

separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"
Coding;

txt = "welcome to the jungle"
x = txt.split()
print(x) 
Output:
['welcome', 'to', 'the', 'jungle']


37. str.splitlines()

    The splitlines() method splits a string into a list. The splitting is done at line breaks.
Syntax: >    string.splitlines(keeplinebreaks)
keeplinebreaks Optional. Specifies if the line breaks should be included (True), or not (False). Default value is False
Coding;
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x) 
Output:
['Thank you for the music', 'Welcome to the jungle']


38. str.startswith()

    The startswith() method returns True if the string starts with the specified value, otherwise False.
Syntax: >    string.startswith(value, start, end)
value Required. The value to check if the string starts with
start Optional. An Integer specifying at which position to start the search
end Optional. An Integer specifying at which position to end the search
Coding;
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x) 
Output:
True


39. str.strip()

    The strip() method removes any leading, and trailing whitespaces.

    Leading means at the beginning of the string, trailing means at the end.

    You can specify which character(s) to remove, if not, any whitespaces will be removed.

Syntax: >    string.strip(characters)

characters Optional. A set of characters to remove as leading/trailing characters
Coding;
txt = "     banana     "
x = txt.strip()
print("of all fruits", x, "is my favorite") 
Output:
of all fruits banana is my favorite


40. str.swapcase()

    The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax: >    string.swapcase()
Coding;
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x) 
Output:
hELLO mY nAME iS peter


41. str.title()

    The title() method returns a string where the first character in every word is upper case. Like a header, or a title.

    If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Syntax: >    string.title()

Coding;

txt = "Welcome to my world"
x = txt.title()
print(x) 
Output:
Welcome To My World


42. str.translate()

    The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.

    Use the maketrans() method to create a mapping table.

    If a character is not specified in the dictionary/table, the character will not be replaced.

    If you use a dictionary, you must use ascii codes instead of characters.

Syntax: >    string.translate(table)

table Required. Either a dictionary, or a mapping table describing how to perform the replace
Coding;
#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict = {8380}
txt = "Hello Sam!"
print(txt.translate(mydict))
Output:
Hello Pam!


43. str.upper()

    The upper() method returns a string where all characters are in upper case.

    Symbols and Numbers are ignored.

Syntax: >    string.upper()

Coding;

txt = "Hello my friends"
x = txt.upper()
print(x)
Output:
HELLO MY FRIENDS


44. str.zfill()

    The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.

    If the value of the len parameter is less than the length of the string, no filling is done.

Syntax: >    string.zfill(len)

len Required. A number specifying the desired length of the string
Coding;
txt = "50"
x = txt.zfill(10)
print(x)
Output:
0000000050




Post a Comment

1Comments

Post a Comment

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!