Python Programming

Python String Functions Or Methods, Python Substring, Python Split String

Description:

Python String Functions- In this tutorial you will learn different string functions or methods in python, And you will also learn how to use these functions or methods in programming.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Python String Functions

You can get a list of all the Functions associated with the string by passing the str function to dir()

>>> dir(str)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',

'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',

'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__

mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',

'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',

'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',

'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',

'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',

'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',

'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Various methods associated with str are displayed

Python String Functions



Python String Functions Syntax:

capitalize() string_name.capitalize():

The capitalize() Python String Functions returns a copy of the string with its first character capitalized and the rest lowercased.

casefold() string_name.casefold():

 The casefold()Python String Functions returns a casefolded copy of the string. Casefolded strings may be used for caseless matching.

center() string_name.center(width[,fillchar]):

The Python String Functions  center() makes string_name centered by taking width parameter into account. Padding is

specified by parameter fillchar. Default filler is a space.

count() string_name.count(substring [,start [, end]]):

The Python String Functions  count(), returns the number of nonoverlapping occurrences of substring in the range [start,

end]. Optional arguments start and end are construed as in slice notation.

endswith() string_name.endswith(suffix[,start[, end]]):

This Python String Functions  endswith(), returns True if the string_name ends with the specified suffix substring, otherwise returns False. With optional start, test beginning at that

position. With optional end, stop associatingat that position.


find() string_name. find(substring[,start[, end]]):

Checks if substring appears in string_name or if substring appears in string_name specified by starting index start and ending index end. Return position of the

first character of the first instance of string substring in string_name, otherwise return –1 if substring not found in string_name.

isalnum() string_name.isalnum():

 The Python String Functions  isalnum() returns Boolean True if all characters in the string are alphanumeric and there is at least one character, else it returns Boolean False.

isalpha() string_name.isalpha() :

The Python String Functions  isalpha(), returns Boolean True if allcharacters in the string are alphabetic and there is at least one character, else it returns Boolean False.

isdecimal() string_name.isdecimal():

The Python String Functions  isdecimal(), returns Boolean True if all characters in the string are decimal characters and there is at least one character, else it returns Boolean False.

isdigit() string_name.isdigit():

The Python String Functions  isdigit() returns Boolean True if all characters in the string are digits and there is at least one character, else it returns Boolean False.

isidentifier() string_name.isidentifier():

The Python String Functions  isidentifier() returns Boolean True if the string is a valid identifier, else it returns Boolean False.

islower() string_name.islower():

 The Python String Functions  islower() returns Boolean True if all characters in the string are lowercase, else it returns Boolean False.

isspace() string_name.isspace():

 The Python String Functions  isspace() returns Boolean True if there are only whitespace characters in the string and there is at least one character, else it returns Boolean False.

isnumeric() string_name.isnumeric():

 The Python String Functions  isnumeric(), returns Boolean True if all characters in the string_name are numeric characters, and there is at least one character, else it returns Boolean

False. Numeric characters include digit letters and all characters that have the Unicode numeric value property.

istitle() string_name.istitle():

 The Python String Functions istitle() returns Boolean True if the string is a title cased string and there is at least one character, else it returns Boolean False.

isupper() string_name.isupper():

The Python String Functions isupper() returns Boolean True if all cased characters in the string are uppercase and there is at least one cased character, else it returns Boolean False.

upper() string_name.upper():

 The Python String Functions upper() converts lowercase letters in string to uppercase. lower() string_name.lower() The method lower() converts uppercase letters in string to lowercase.

ljust() string_name.ljust(width[,fillchar]):

In the Python String Functions ljust(), when you provide the string to the method ljust(), it returns the string left justified. Total length of the string is defined in first parameter of method width. Padding is done as defined in second parameter

fillchar. (default is space).

rjust() string_name.rjust(width[,fillchar]):

In the method rjust(), when you provide the string to the method rjust(), it returns the string right justified. The total length of string is defined in the first parameter of the method, width. Padding is done as defined in

second parameter fillchar. (default is space).

title() string_name.title():

 The Python String Functions title() returns “titlecased” versions of string, that is, all words begin with uppercase characters and the rest are lowercase.

swapcase() string_name.swapcase():

 The Python String Functions swap case() returns a copy of the string with uppercase characters converted to lowercase and vice versa.

splitlines() string_name.splitlines([keepends]):

The Python String method splitlines() returns a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the collateral

list unless keepends is given and true.


startswith() string_name.startswith(prefix[,start[, end]]):

The Python String method startswith() returns Boolean True if the string starts with the prefix, otherwise return False. With optional start, test string_name beginning at that

position. With optional end, stop comparing string_name at that position.

strip() string_name.strip([chars]):

 The Python String methods lstrip() returns a copy of the string_name in which specified chars have been stripped from both side of the string. If char is not specified then space is taken as default.

rstrip() string_name.rstrip([chars]):

 The Python String methods rstrip() removes all trailing whitespace of string_name.

lstrip() string_name.lstrip([chars]):

 The Python String Functions lstrip() removes all leading whitespace in string_name.

replace() string_name. replace(old, new[, max]):

The Python String methods replace() replaces all occurrences of old in string_name with new. If the optional argument max is given, then only the first max occurrences are replaced.

zfill() string_name.zfill(width):

 The Python String method zfill() pads the string_name on the left with zeros to fill width.

Note: Replace the word string_name mentioned in the syntax with the actual string name in your code.

I used some of Python String methods s in programming For example,

>>> fact = "Abraham Lincoln was also a champion wrestler"
>>> fact.isalnum()
False
>>> "sailors".isalpha()
True
>>> "2018".isdigit()
True
>>> fact.islower()
False
>>> "TSAR BOMBA".isupper()
True
>>> "columbus".islower()
True
>>> warriors = "ancient gladiators were vegetarians"
>>> warriors.endswith("vegetarians")
True
>>> warriors.startswith("ancient")
True
>>> warriors.startswith("A")
False
>>> warriors.startswith("a")
True
>>> "cucumber".find("cu")
0
>>> "cucumber".find("um")
3
>>> "cucumber".find("xyz")
-1
>>> warriors.count("a")
5
>>> species = "charles darwin discovered galapagos tortoises"
>>> species.capitalize()
'Charles darwin discovered galapagos tortoises'
>>> species.title()
'Charles Darwin Discovered Galapagos Tortoises'
>>> "Tortoises".lower()
'tortoises'
>>> "galapagos".upper()
'GALAPAGOS'
>>> "Centennial Light".swapcase()
'cENTENNIAL lIGHT'
>>> "history does repeat".replace("does", "will")
'history will repeat'
>>> quote = " Never Stop Dreaming "
>>> quote.rstrip()
' Never Stop Dreaming'
>>> quote.lstrip()
'Never Stop Dreaming '
>>> quote.strip()
'Never Stop Dreaming'
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> "scandinavian countries are rich".center(40)
'scandinavian countries are rich'

Various operations on strings are carried out using string  methods. String methods like capitalize(), lower(), upper(), swapcase(), title() and count() are used for conversion purpose. String methods like islower(), isupper(), isdecimal(), isdigit(), isnumeric(), isalpha() and isalnum() are used for comparing strings. Some of the string methods used for padding are rjust(), ljust(), zfill() and center(). The string method find() is used to find

substring in an existing string. You can use string methods like replace(), join(), split() and splitlines() to replace a string in Python.


Example Write a Python Program That Accepts a Sentence and Calculate the Number of Words, Digits, Uppercase Letters and Lowercase Letters:

def string_processing(user_string):
word_count = 0
digit_count = 0
upper_case_count = 0
lower_case_count = 0
for each_char in user_string:
if each_char.isdigit():
digit_count += 1
elif each_char.isspace():
word_count += 1
elif each_char.isupper():
upper_case_count += 1
136 Introduction to Python Programming
elif each_char.islower():
lower_case_count += 1
else:
pass
print(f"Number of digits in sentence is {digit_count}")
print(f"Number of words in sentence is {word_count + 1}")
print(f"Number of upper case letters in sentence is {upper_case_count}")
print(f"Number of lower case letters in sentence is {lower_case_count}")
def main():
user_input = input("Enter a sentence ")
string_processing(user_input)   
if __name__ == "__main__":
main()
Output
Enter a sentence The Eiffel Tower in Paris is 324m tall
Number of digits in sentence is 3
Number of words in sentence is 8
Number of upper case letters in sentence is 4
Number of lower case letters in sentence is 24

Initially the variables word_count, digit_count, upper_case_count and lower_case_count are assigned to zero. For each character traversed through the string using for loop, the character is checked to see whether it is a digit or uppercase or lowercase. If any of these is True, then the corresponding variable digit_count or upper_case or lower_case is incremented by one. If a space is encountered, then it indicates the end of a word and the variable word_count is incremented by one. The number of whitespaces + 1 indicates the total number of words in a sentence. The pass statement allows you to handle the shape without the loop being impacted in any way. The pass is a null statement and nothing happens when pass is executed. It is actionable as a placeholder when a statement is obligatory syntactically, but no code needs to be executed.



Example Write a Python Program to Convert Uppercase Letters to Lowercase and Vice Versa

def case_conversion(user_string):
convert_case = str()
for each_char in user_string:
if each_char.isupper():
convert_case += each_char.lower()
else:
convert_case += each_char.upper()
137 Strings
print(f"The modified string is {convert_case}")
def main():
input_string = input("Enter a string ")
case_conversion(input_string)
if __name__ == "__main__":
main()
Output
Enter a string ExquiSITE
The modified string is eXQUIsite

Each character in the string user_string is traversed using for loop and check whether it is in uppercase. If Boolean True then convert the character to lowercase and concatenate it to convert_case string else convert the character to uppercase and concatenate with convert_case string. Finally, print the convert_case flipped string.


Example Write a Python Program to Replace Comma-Separated Words with Hyphens and Print Hyphen-Separated Words in Ascending Order

def replace_comma_with_hyphen(comma_separated_words):
split_words = comma_separated_words.split(",")
split_words.sort()
hyphen_separated_words = "-".join(split_words)
print(f"Hyphen separated words in ascending order are
'{hyphen_separated_words}'")
def main():
comma_separated_words = input("Enter comma separated words ")
replace_comma_with_hyphen(comma_separated_words)
if __name__ == "__main__":
main()
Output
Enter comma separated words global,education
Hyphen separated words in ascending order are 'education-global'

The user enters a sequence of words separated by a comma which is passed as an argument to replace_comma_with_hyphen() function. The comma-separated words are split based on “,” (comma) and assigned to split_words as a list of string items. Sort the words in the list. Join the words in the list with a hyphen between them using join() function. Print the sorted and hyphen-separated sequence of words.


Example Write a Python Program to Count the Occurrence of User-Entered Words in a Sentence

def count_word(word_occurrence, user_string):
word_count = 0
for each_word in user_string.split():
if each_word == word_occurrence:
word_count += 1
print(f"The word '{word_occurrence}' has occurred {word_count} times")
def main():
input_string = input("Enter a string ")
user_word = input("Enter a word to count its occurrence ")
count_word(user_word, input_string)
if __name__ == "__main__":
main()
Output
Enter a string You cannot end a sentence with because because because is a conjunction
Enter a word to count its occurrence because
The word 'because' has occurred 3 times

The user enters a string to count its occurrence in a sentence and is stored in user_word  variable and the user entered sentence is stored in input_string  variable. These are passed as parameters to count_word() function definition. The sentence is split using space as the reference to a list of words and use for loop to iterate through each word. Check whether each word is equal to the user entered string value stored in word_occurence string variable.

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button