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

Python String Functions

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.



Python String Functions

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

 

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,

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:

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

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

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

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.



Python String Functions Related Article:

Python String Format String Specifiers, Escape Sequences, Raw Format

 

Recommended For You

Leave a Reply

%d bloggers like this: