21 String Methods in Python: Very Important Methods for Empowering Code

string methods in python

Dear friends, let’s discuss string methods in python with examples:

1) capitalize( )

Syntaxcapitalize( )
Purpose1. Return copy of string with first character capitalized and remaining characters in lowercase.
2. It has no argument.

Example of capitalize( ) string methods in python:

# Input string
text = "python programming is fun"

# Apply the capitalize() method
capitalized_text = text.capitalize()

# Output the original and capitalized strings
print("Original String:", text)
print("Capitalized String:", capitalized_text)


Output:

Original String: python programming is fun

Capitalized String: Python programming is fun

2) casefold( )

Syntaxcasefold( )
Purpose1. Returns casefolded copy of string, used for caseless matching.
2. It has no argument.

Example of casefold( ) string methods in python:

# Input string
text = "ThIs Is A CaSeFoLd ExAmPlE."

# Apply the casefold() method
casefolded_text = text.casefold()

# Output the original and casefolded strings
print("Original String:", text)
print("Casefolded String:", casefolded_text)


Output:

Original String: ThIs Is A CaSeFoLd ExAmPlE.

Casefolded String: this is a casefold example.

3) center( )

Syntaxcenter(width[,fillchar])
Purpose1. Returns string centered in a string of length width, padding by specified fillchar.
2. If width is less than or equal to length of string then returns original string.
3. Fillchar must be exactly one character long.

Example of center( ) string methods in python:

# Input string
text = "Codejunctionpro"

# Apply the center() method to center-align the string in a width of 12 characters, using '-' as padding
centered_text = text.center(12, '-')

# Output the centered string
print(centered_text)


Output:

Codejunctionpro

4) count( )

Syntaxcount(sub[,start[,end]])
Purpose1. Returns total non-overlapping occurrences of substring in the range start to end.
2. It does not double up on characters that have been counted once.
3. Start and end represent position of string slice.
4. Start and end are optional.

Example of count( ) string methods in python:

# Input string
text = "Python is an easy-to-learn programming language. Python is versatile and Python is fun."

# Count the number of occurrences of the word "Python" in the string
count = text.count("Python")

# Output the result
print("The word 'Python' appears", count, "times in the text.")

Output:

The word 'Python' appears 3 times in the text.

5) endswith( )

Syntaxendswith(suffix[,start[,end]])
Purpose1. Check whether string ends with specified suffix.
2. If does not, it returns false.
3. Start and end represent position of string slice.
4. Start and end are optional.

Example of endswith( ) string methods in python:

# Input string
text = "Hello, World"

# Check if the string ends with "World"
result1 = text.endswith("World")

# Check if the string ends with "Hello"
result2 = text.endswith("Hello")

# Output the results
print(f'Does the string end with "World"? {result1}')
print(f'Does the string end with "Hello"? {result2}')

Output:

Does the string end with "World"? True

Does the string end with "Hello"? False

6) expandtabs( )

Syntaxexpandtabs(tabsize)
Purpose1. Returns copy of a string where all tab characters are replaced by one or more spaces.
2. Tab position occurs at every tabsize characters.
3. Default is 8

Example of expandtabs( ) string methods in python:

# Input string with tab characters
text = "Python\tis\tawesome"

# Use the expandtabs() method to replace tabs with spaces
expanded_text = text.expandtabs(4)

# Output the expanded string
print("Original String:")
print(text)
print("\nExpanded String:")
print(expanded_text)

Output:

Original String:
Python	is	awesome

Expanded String:
Python  is  awesome

7) find( )

Syntaxfind(sub[,start[,end]]))
Purpose1. Returns lowest index in the string where substring found within slice.
2. If not found, return -1
3. Start and end represent position of string slice.
4. Start and end are optional.
5. It is only used to find the position of the substring.

Example of find( ) string methods in python:

# Input string
text = "Python is a powerful programming language. Python is versatile and Python is fun."

# Find the first occurrence of "Python" in the string
index = text.find("Python")

# Output the result
if index != -1:
    print(f"'Python' found at index {index}")
else:
    print("'Python' not found in the string.")

Output:

'Python' found at index 0

8) format( )

Syntaxformat(*args,**kwargs)
Purpose1. Formats a string.
2. String may contain literal text or replacement fields delimited by { }
3. It returns copy of formatted string with replacement.
4. Replacement field may contain either numeric index of positional argument or name of keyword argument.

Example of format( ) string methods in python:

# Define variables
name = "John"
age = 30

# Create a formatted string using the format() method
formatted_string = "My name is {} and I am {} years old.".format(name, age)

# Output the formatted string
print(formatted_string)

Output:

My name is John and I am 30 years old.

9) index( )

Syntaxindex(sub[,start[,end]])
Purpose1. Similar to find( ) but in find returns -1 if not found whereas index( ) returns ValueError if not found.

Example of index( ) string methods in python:

# Input string
text = "Python is a versatile programming language. Python is fun."

try:
    # Find the index of the first occurrence of "Python" in the string
    index = text.index("Python")
    print("'Python' found at index", index)
except ValueError:
    print("'Python' not found in the string.")

Output:

'Python' found at index 0

10) isalnum( )

Syntaxisalnum( )
Purpose1. Checks whether all characters in non-empty string are alphanumeric.
2. It has no argument.

Example of isalnum( ) string methods in python:

# Input strings
string1 = "Python3"
string2 = "Python 3"
string3 = "12345"

# Check if the strings are alphanumeric
result1 = string1.isalnum()
result2 = string2.isalnum()
result3 = string3.isalnum()

# Output the results
print(f'Is "{string1}" alphanumeric? {result1}')
print(f'Is "{string2}" alphanumeric? {result2}')
print(f'Is "{string3}" alphanumeric? {result3}')

Output:

Is "Python3" alphanumeric? True
Is "Python 3" alphanumeric? False
Is "12345" alphanumeric? True

11) isalpha( )

Syntaxisalpha( )
Purpose1. Verify whether all characters in string are alphabetic, if yes returns True otherwise False.
2. It has no argument.

Example of isalpha( ) string methods in python:

# Input strings
string1 = "Python"
string2 = "Python3"
string3 = "12345"

# Check if the strings are alphabetic
result1 = string1.isalpha()
result2 = string2.isalpha()
result3 = string3.isalpha()

# Output the results
print(f'Is "{string1}" alphabetic? {result1}')
print(f'Is "{string2}" alphabetic? {result2}')
print(f'Is "{string3}" alphabetic? {result3}')

Output:

Is "Python" alphabetic? True
Is "Python3" alphabetic? False
Is "12345" alphabetic? False

12) isdecimal( )

Syntaxisdecimal( )
Purpose1. Verify whether all characters in string are decimal digits.
2. If yes, returns True otherwise returns False.
3. It has no argument.

Example of isdecimal( ) string methods in python:

# Input strings
string1 = "12345"
string2 = "123.45"
string3 = "Python"

# Check if the strings are composed of decimal digits
result1 = string1.isdecimal()
result2 = string2.isdecimal()
result3 = string3.isdecimal()

# Output the results
print(f'Is "{string1}" composed of decimal digits? {result1}')
print(f'Is "{string2}" composed of decimal digits? {result2}')
print(f'Is "{string3}" composed of decimal digits? {result3}')

Output:

Is "12345" composed of decimal digits? True
Is "123.45" composed of decimal digits? False
Is "Python" composed of decimal digits? False

13) isdigit( )

Syntaxisdigit( )
Purpose1. Verify and returns True if all characters in string are digits.
2. Otherwise returns False.
3. It has no argument.

Example of isdigit( ) string methods in python:

# Input strings
string1 = "12345"
string2 = "123.45"
string3 = "Python"

# Check if the strings consist of digits
result1 = string1.isdigit()
result2 = string2.isdigit()
result3 = string3.isdigit()

# Output the results
print(f'Is "{string1}" composed of digits? {result1}')
print(f'Is "{string2}" composed of digits? {result2}')
print(f'Is "{string3}" composed of digits? {result3}')

Output:

Is "12345" composed of digits? True
Is "123.45" composed of digits? False
Is "Python" composed of digits? False

14) isidentifier( )

Syntaxisidentifier( )
Purpose1. Returns True if the string is valid identifier

Example of isidentifier( ) string methods in python:

# Input strings
string1 = "my_variable"
string2 = "123variable"
string3 = "for"
string4 = "my-variable"

# Check if the strings are valid Python identifiers
result1 = string1.isidentifier()
result2 = string2.isidentifier()
result3 = string3.isidentifier()
result4 = string4.isidentifier()

# Output the results
print(f'Is "{string1}" a valid Python identifier? {result1}')
print(f'Is "{string2}" a valid Python identifier? {result2}')
print(f'Is "{string3}" a valid Python identifier? {result3}')
print(f'Is "{string4}" a valid Python identifier? {result4}')

Output:

Is "my_variable" a valid Python identifier? True
Is "123variable" a valid Python identifier? False
Is "for" a valid Python identifier? True
Is "my-variable" a valid Python identifier? False

15) islower( )

Syntaxislower( )
Purpose1. Verify and returns True if all alphabets in string are lowercase.
2. It has no argument.

Example of islower( ) string methods in python:

# Input strings
string1 = "hello world"
string2 = "Hello World"
string3 = "pythoniscool"

# Check if the strings are in lowercase
result1 = string1.islower()
result2 = string2.islower()
result3 = string3.islower()

# Output the results
print(f'Is "{string1}" in lowercase? {result1}')
print(f'Is "{string2}" in lowercase? {result2}')
print(f'Is "{string3}" in lowercase? {result3}')


Output:

Is "hello world" in lowercase? True
Is "Hello World" in lowercase? False
Is "pythoniscool" in lowercase? True

16) isnumeric( )

Syntaxisnumeric
Purpose1. Verify and return True if all characters in string are numeric otherwise returns False.
2. It has no argument.

Example of isnumeric( ) string methods in python:

# Input strings
string1 = "12345"
string2 = "½"
string3 = "3.14"
string4 = "Python"

# Check if the strings are numeric
result1 = string1.isnumeric()
result2 = string2.isnumeric()
result3 = string3.isnumeric()
result4 = string4.isnumeric()

# Output the results
print(f'Is "{string1}" numeric? {result1}')
print(f'Is "{string2}" numeric? {result2}')
print(f'Is "{string3}" numeric? {result3}')
print(f'Is "{string4}" numeric? {result4}')

Output:

Is "12345" numeric? True
Is "½" numeric? True
Is "3.14" numeric? False
Is "Python" numeric? False

17) isprintable( )

Syntaxisprintable( )
Purpose1. Verify and returns True if all characters in string are printable or string is empty. Otherwise returns False.
2. It has no argument.

Example of isprintable( ) string methods in python:

# Input strings
string1 = "Hello, World!"
string2 = "Line 1\nLine 2"
string3 = "Python is fun."

# Check if the strings are printable
result1 = string1.isprintable()
result2 = string2.isprintable()
result3 = string3.isprintable()

# Output the results
print(f'Is "{string1}" printable? {result1}')
print(f'Is "{string2}" printable? {result2}')
print(f'Is "{string3}" printable? {result3}')

Output:

Is "Hello, World!" printable? True
Is "Line 1
Line 2" printable? False
Is "Python is fun." printable? True

18) isspace( )

Syntaxisspace( )
Purpose1. Returns True if string contains only whitespaces and string is not empty.

Example of isspace( ) string methods in python:

# Input strings
string1 = "    "  # Contains only spaces
string2 = "Hello World"  # Contains letters and spaces
string3 = "\t\t"  # Contains only tabs
string4 = "  \t\n"  # Contains spaces, tabs, and newlines

# Check if the strings consist of whitespace characters
result1 = string1.isspace()
result2 = string2.isspace()
result3 = string3.isspace()
result4 = string4.isspace()

# Output the results
print(f'Is "{string1}" composed of whitespace characters? {result1}')
print(f'Is "{string2}" composed of whitespace characters? {result2}')
print(f'Is "{string3}" composed of whitespace characters? {result3}')
print(f'Is "{string4}" composed of whitespace characters? {result4}')

Output:

Is "    " composed of whitespace characters? True
Is "Hello World" composed of whitespace characters? False
Is "		" composed of whitespace characters? True
Is "  	
" composed of whitespace characters? True

19) istitle( )

Syntaxistitle( )
Purpose1. If given non-empty string is titlecased i.e. first character of all words are capital except uncased characters.
2. It has no argument.

Example of istitle( ) string methods in python:

# Input strings
string1 = "This Is a Title"
string2 = "This is Not a Title"
string3 = "title Case"
string4 = "title case"

# Check if the strings are in title case
result1 = string1.istitle()
result2 = string2.istitle()
result3 = string3.istitle()
result4 = string4.istitle()

# Output the results
print(f'Is "{string1}" in title case? {result1}')
print(f'Is "{string2}" in title case? {result2}')
print(f'Is "{string3}" in title case? {result3}')
print(f'Is "{string4}" in title case? {result4}')

Output:

Is "This Is a Title" in title case? False
Is "This is Not a Title" in title case? False
Is "title Case" in title case? False
Is "title case" in title case? False

20) isupper( )

Syntaxisupper( )
Purpose1. Verify and returns True if all alphabets in string are in uppercase. otherwise returns False.
2. It has no argument.

Example of isupper( ) string methods in python:

# Input strings
string1 = "HELLO WORLD"
string2 = "Hello World"
string3 = "PYTHONISCOOL"

# Check if the strings are in uppercase
result1 = string1.isupper()
result2 = string2.isupper()
result3 = string3.isupper()

# Output the results
print(f'Is "{string1}" in uppercase? {result1}')
print(f'Is "{string2}" in uppercase? {result2}')
print(f'Is "{string3}" in uppercase? {result3}')

Output:

Is "HELLO WORLD" in uppercase? True
Is "Hello World" in uppercase? False
Is "PYTHONISCOOL" in uppercase? True

21) join( )

Syntaxjoin(iterable)
Purpose1. Concatenates string with iterable and returns concatenated string.
2. It takes exactly one argument.

Example of join( ) string methods in python:

# List of strings
words = ["Hello", "World", "Python", "Programming"]

# Define a delimiter
delimiter = ", "

# Use the join() method to concatenate the list of strings
result = delimiter.join(words)

# Output the result
print(result)


Output:

Hello, World, Python, Programming

3 thoughts on “21 String Methods in Python: Very Important Methods for Empowering Code

  1. Is it acceptable if I duplicate your article? Your commitment to educating and empowering others is truly admirable, and I’m grateful for the impact it has had on me. Can you visit my website too?? at Kampus Terbaik Thanks! ID : CMT-LE8A66XF5F106FHSAB

Leave a Reply

Your email address will not be published. Required fields are marked *