Showing posts with label Python string. Show all posts
Showing posts with label Python string. Show all posts

Friday, December 30, 2022

Python Program to Check if Strings Anagram or Not

In this post we'll see a Python program to check if two strings are anagrams or not.

Anagram Strings

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "silent" and "listen", "School Master" and "The Classroom".

Strings Anagram or not Python program

Python program to check whether the given strings are anagrams or not can be written by using one of the following options.

  1. Sorting both the strings
  2. By iterating one of the string character by character and verifying that the second string has the same characters present.

1. By sorting string

If you are using sorting logic to find whether strings are anagram or not in Python, just sort both the strings and compare if content is equal that means strings are anagram.

You can use sorted() in built function in Python to sort which returns a new sorted list from the items in iterable. Before sorting the string you can also change the case of the strings and remove spaces from the string.

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)

  if sorted(temp1) == sorted(temp2):
    print(s1, 'and', s2, 'are anagrams')
  else:
    print(s1, 'and', s2, 'are not anagrams')
        
is_anagram('silent', 'listen')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- silent
s2 in lower case and no spaces- listen
silent and listen are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

2. By Iteration

If you are using loop to find whether strings are anagram or not in Python, then iterate one string char by char and check whether that character exists in another string or not, for that you can use find() method.

If character exists in the second string then delete that occurrence of the character from the string too so that same character is not found again (if char occurs more than once).

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)
  # if both strings are not of same length then not anagrams
  if len(temp1) != len(temp2):
    print(s1, 'and', s2, 'are not anagrams')

  for c in temp1:
    index = temp2.find(c);
    if index == -1:
      print(s1, 'and', s2, 'are not anagrams')
      break
    else:
      # delete the found character so that same character is
      # not found again
      temp2.replace(c, "", 1)
  else:
    print(s1, 'and', s2, 'are anagrams')

is_anagram('Hello', 'OHell')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- hello
s2 in lower case and no spaces- ohell
Hello and OHell are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

That's all for this topic Python Program to Check if Strings Anagram or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check Whether String is Palindrome or Not
  3. Python Program to Check Prime Number
  4. Removing Spaces From String in Python
  5. Accessing Characters in Python String

You may also like-

  1. Python continue Statement With Examples
  2. Polymorphism in Python
  3. Functions in Python
  4. Constructor in Python - __init__() function
  5. Switch Case Statement in Java
  6. HashMap in Java With Examples
  7. Convert Numbers to Words Java Program
  8. Configuring DataSource in Spring Framework

Thursday, December 22, 2022

Python Program to Check Whether String is Palindrome or Not

This post is about writing a Python program to find whether a given string is a palindrome or not.

A String is a palindrome if reverse of the string is same as the original string. For example "madam" is a palindrome as reverse of the madam is again madam another example is "malayalam".

Logic for the palindrome program

  1. One way to find whether a given string is a palindrome or not is to reverse the given string. If reverse of the string and original string are equal that means string is a palindrome.
  2. Another way is to iterate string and compare characters at both ends (start and end) for equality. Any time if a character is found that is not equal before start > end then it is not a palindrome.

1. Reversing string and comparing

For reversing a string in Python best way is to use string slicing with a negative increment number to get the string backward. Once you have the reversed string compare it with original string to check if both are equal or not.

import re
def reverse_string(string):
  rstring = string[::-1]
  return rstring

def is_palindrome(s):
  rstring = reverse_string(s)
  return True if (rstring == s) else False

s = "madam"
# if more than one word remove spaces
# s = re.sub("^\\s+|\\s+$|\\s+", "", s)
# print(s)
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

madam is a palindrome

Note that if string has more than one word like “nurses run” then remove the spaces from the string before checking for palindrome string. You can uncomment the commented lines for that.

2. Comparing characters from start and end of the string

You can also compare characters from both ends of the string, if any time a character is found which is not equal then the passed string is not a palindrome. Python program to find whether given string is a palindrome or not using this logic can be written both as a recursive function and iterative function.

Recursive function is given first.

def is_palindrome(s):
  print(s)
  if len(s) == 0:
    return True
  else:
    if s[0] == s[-1]:
      # remove start and end characters
      return is_palindrome(s[1:len(s)-1])
    else:
      return False

s = "radar"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

radar
ada
d

radar is a palindrome

As an iterative function.

def is_palindrome(s):
  # last index
  end = len(s) - 1;
  for start in range(len(s)):
    # all the characters are compared and are equal
    if start > end:
      return True
    else:
      # compare characters at both ends
      if s[start] == s[end]:
        # move towards left
        end -= 1
      else:
        return False

s = "malayalam"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

malayalam is a palindrome

That's all for this topic Python Program to Check Whether String is Palindrome or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Reverse a String
  2. Python Program to Display Armstrong Numbers
  3. Getting Substring in Python String
  4. Python String isnumeric() Method
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Ternary Operator in Python
  2. Operator Overloading in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Java CountDownLatch With Examples
  6. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  7. How to Write Excel File in Java Using Apache POI
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

Tuesday, November 29, 2022

Python Program to Reverse a String

In this post we'll see how to write a Python program to reverse a string, there are several options to do that, the options given in this post are listed below-

  1. Using a loop to reverse a string.
  2. Using a recursive function.
  3. Using string slicing
  4. Using reversed() function and join() method

Using loop to reverse a string Python program

If you are asked to write Python program to reverse a string without using any inbuilt function or string method you can use a loop to add characters of a string in a reverse order in each iteration to form a new String.

def reverse_string(string):
  rstring = ''
  for char in string:
    rstring = char + rstring
  return rstring

s = 'Python Programming'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

Using recursive function to reverse a string

In recursive function, in each recursive call to the function you pass the sliced string where start index is 1 (i.e. exclude first char (index 0) in each call) and add the first char of the passed String at the end.

def reverse_string(string):
  if len(string) == 1:
    return string
  else:
    return reverse_string(string[1:]) + string[0]

s = 'Hello World'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

Using string slicing

One of the best way to reverse a string in Python is to use String slicing. In string in Python you can also use negative indexing. When negative number is used as index, String is accessed backward so -1 refers to the last character, -2 second last and so on. Thus, by providing increment_step as -1 in string slicing you can reverse a string.

def reverse_string(string):
  reversed = s[::-1]
  return reversed

s = 'Hello World'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Hello World Reversed String- dlroW olleH

Using reversed() function and join() method

In built function reversed() in Python returns a reverse iterator. Python String join() method returns a string which is created by concatenating all the elements in an iterable. By combining both of these you can get a reversed string in Python.

def reverse_string(string):
  rstring = "".join(reversed(string))
  return rstring

s = 'Python Programming'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

That's all for this topic Python Program to Reverse a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Program to Display Armstrong Numbers
  4. Check String Empty or Not in Python
  5. Python Functions : Returning Multiple Values

You may also like-

  1. Python assert Statement
  2. Operator Overloading in Python
  3. Nonlocal Keyword in Python With Examples
  4. User-defined Exceptions in Python
  5. How ArrayList Works Internally in Java
  6. Type Erasure in Java Generics
  7. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  8. Spring Object XML Mapping (OXM) Castor Example

Tuesday, November 15, 2022

Convert String to float in Python

In this post we’ll see how to convert String to float in Python.

If you have a float represented as String literal then you need to convert it to float value if you have to use it in any arithmetic operation.

For example-

num1 = "50.56"
num2 = 20.45
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 14, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "float") to str

As you can see num1 variable is of type string so Python tries to concatenate num2 to num1 rather than adding them. In such scenario you need to convert string to float.

Python program - convert String to float

To convert a Python String to a float pass that String to float() function which returns a float object constructed from the passed string.

num1 = "50.56"
num2 = 20.45
result = float(num1) + num2
print("Sum is-", result)

Output

Sum is- 71.01

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to float, ValueError is raised. If you are not sure about the passed number it is better to use try and except for exception handling.

For example in the following Python function string ‘abc’ is passed as one of the argument value which results in ValueErorr being raised while converting it.

def add(num1, num2):
  try:
    result = float(num1) + float(num2)
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add('abc', 10)

Output

Error while conversion: could not convert string to float: 'abc'

Getting integer part of the decimal number

If there is a decimal number stored as a string and you want only the integer part then directly using int() function results in error. You have to first convert string to float and then to int.

num = "50.56"
# Causes error
int_num = int(num) 
print("Integer part is-", int_num)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    int_num = int(num)
ValueError: invalid literal for int() with base 10: '50.56'

Correct way

num = "50.56"
int_num = int(float(num))
print("Integer part is-", int_num)

Output

Integer part is- 50

That's all for this topic Convert String to float in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Number of Words in a String
  3. Python String isnumeric() Method
  4. Operator Overloading in Python
  5. Check String Empty or Not in Python

You may also like-

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Convert String to float in Java
  6. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  7. intern() Method in Java String
  8. Java Exception Handling Tutorial

Sunday, September 11, 2022

Python Program to Count Occurrences of Each Character in a String

In this post we’ll see how to write a Python program to count occurrences of each character or to count frequency of character in a String.

1. If you have to write the Python program to count frequency of each character without using any String method then you can write it using an outer and inner for loop. In the outer loop take the character at index 0 and in the inner loop check if such character is found again in the string, if yes then increment count.

replace() method of the str class is used to remove all the occurrences of the character for which count is done so that same character is not picked again.

def count_char(text):
  for i in range(len(text)):
    if len(text) == 0:
      break;
    ch = text[0]
    # don't count frequency of spaces
    if ch == ' ' or ch == '\t':
        continue
    count = 1
    for j in range(1, len(text)):
      if ch == text[j]:
        count += 1
    # replace all other occurrences of the character
    # whose count is done, strip() is required for 
    # scenario where first char is replaced and there is 
    # space after that
    text = text.replace(ch, '').strip()
    print(ch + " - ", count)

count_char('netjs blog for Python')

Output

n -  2
e -  1
t -  2
j -  1
s -  1
b -  1
l -  1
o -  3
g -  1
f -  1
r -  1
P -  1
y -  1
h -  1

2. You can use count() method in Python which is used to count the number of occurrences of a specific substring.

def count_char(text):
  for i in range(len(text)):
    if len(text) == 0:
      break;
    ch = text[0]
    if ch == ' ' or ch == '\t':
      continue
    print(ch + " - ", text.count(ch))
    text = text.replace(ch, '').strip()

count_char('netjs java spring python')

Output

n -  3
e -  1
t -  2
j -  2
s -  2
a -  2
v -  1
p -  2
r -  1
i -  1
g -  1
y -  1
h -  1
o -  1

3. You can also use Dictionary to count occurrences of each character in the String. Character is stored as a key in dictionary and for each character it is checked if that character already exists as a key in dictionary or not. If it exists then increment the value associated with that key by 1, if such a key doesn’t exist then add it to the dictionary with value as 1.

def count_char(text):
  count = {}
  for ch in text:
    # don't count frequency of spaces
    if ch == ' ' or ch == '\t':
      continue
    # If char already in dictionary increment count
    # otherwise add char as key and 1 as value
    if ch in count:
      count[ch] += 1
    else:
      count[ch] = 1
    for k, v in count.items():
      print('Charcater {} occurs {} times'.format(k,v))

count_char('netjs java spring python')

Output

Charcater n occurs 3 times
Charcater e occurs 1 times
Charcater t occurs 2 times
Charcater j occurs 2 times
Charcater s occurs 2 times
Charcater a occurs 2 times
Charcater v occurs 1 times
Charcater p occurs 2 times
Charcater r occurs 1 times
Charcater i occurs 1 times
Charcater g occurs 1 times
Charcater y occurs 1 times
Charcater h occurs 1 times
Charcater o occurs 1 times

That's all for this topic Python Program to Count Occurrences of Each Character in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Number of Words in a String
  2. Removing Spaces From String in Python
  3. Check String Empty or Not in Python
  4. Python String isdigit() Method
  5. pass Statement in Python

You may also like-

  1. raise Statement in Python Exception Handling
  2. Magic Methods in Python With Examples
  3. self in Python
  4. Check if Given String or Number is a Palindrome Java Program
  5. instanceof Operator in Java With Examples
  6. Optional Class in Java With Examples
  7. Spring depends-on Attribute and @DependsOn With Examples
  8. @Import Annotation in Spring JavaConfig

Friday, September 2, 2022

Convert String to int in Python

In this post we’ll see how to convert String to int in Python.

If you have an integer represented as String literal then you need to convert it to integer value if you have to use it in any arithmetic operation.

For example-

num1 = "50"
num2 = 20
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "int") to str

As you can see since the first operand is string so Python tries to concatenate the second operand to the first rather than adding them. In such scenario you need to convert string to int.

Python program - convert String to int

To convert a Python String to an int pass that String to int() function which returns an integer object constructed from the passed string.

num1 = "50"
num2 = 20
# converting num1 to int
result = int(num1) + num2
print("Sum is-", result)

Output

Sum is- 70

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to int, ValueError is raised. While doing such conversions it is better to use try and except for exception handling.

def add():
  try:
    num1 = "abc"
    num2 = 20
    # converting num1 to int
    result = int(num1) + num2
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add()

Output

Error while conversion: invalid literal for int() with base 10: 'abc'

Converting String with commas to int

If String variable is storing a number with commas (as example str_num="6,00,000") then one of the option is to use replace() method of the str class to remove commas before converting string to int.

def add():
  try:
    num1 = "6,45,234"
    num2 = 230000
    # converting num1 to int
    result = int(num1.replace(',', '')) + num2
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add()

Output

Sum is- 875234

That's all for this topic Convert String to int in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to float in Python
  2. Python Program to Display Fibonacci Series
  3. Python String isdigit() Method
  4. Operator Overloading in Python
  5. Removing Spaces From String in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Python Functions : Returning Multiple Values
  3. Python Exception Handling Tutorial
  4. Local, Nonlocal And Global Variables in Python
  5. Converting String to int in Java
  6. ArrayList in Java With Examples
  7. Lambda Expressions in Java 8
  8. Interface Default Methods in Java 8

Sunday, May 1, 2022

Python Program to Count Number of Words in a String

In this post we’ll see how to write a Python program to count number of words in a String. This program can be written in various ways and this post shows some of the ways.

1. If you can’t use any of the methods of the String class then Python program for counting number of words can be written by iterating each character of the string using for loop and check if the character is space (' '), tab('\t') or linefeed ('\n'). If such a character is found that means a new word is starting so the count is incremented by 1.

def number_words(text):
  print('String-', text)
  no_of_words = 1
  for ch in text:
    if (ch == ' ' or ch == '\t' or ch == '\n'):
      no_of_words += 1
  print('Total number of words in String', no_of_words)

number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

String- This is a test string
Total number of words in String 5
String- This Python program counts number of words in a String.
Total number of words in String 10

2. Using split() method in Python you can count words in a String. Whitespaces are used as a separator by default in split() method and the method returns a list of the words in the string. By using len() function you can get the length of that list which gives the number of words in a String.

def number_words(text):
  print('Total number of words in String', len(text.split()))
    
number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

Total number of words in String 5
Total number of words in String 10

3. You can also write Python program to count number of words in a String using regular expressions in Python. In the program two methods split() and findall() are used.

The split() method splits the string as per the passed regular expression and the split words are returned as a list.

The findall() method returns all occurrences of the matching string as a list.

\s sequence character represents white space, \s+ means 1 or more white spaces.

\W sequence character represents non-alphanumeric, \W+ means 1 or more non-alphanumeric characters.

import re

def number_words(text):
  print('Total number of words in String', len(re.findall(r'\W+', text)))
  print('Total number of words in String', len(re.split(r'\s+', text)))

number_words('This is a Python program')
s = 'This Python program\'s job is to find number of words in a String'
number_words(s)

Output

Total number of words in String 4
Total number of words in String 5
Total number of words in String 13
Total number of words in String 13

That's all for this topic Python Program to Count Number of Words in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Changing String Case in Python
  3. Python String split() Method
  4. Python count() method - Counting Substrings
  5. Python while Loop With Examples

You may also like-

  1. User-defined Exceptions in Python
  2. Namespace And Variable Scope in Python
  3. Multiple Inheritance in Python
  4. ListIterator in Java
  5. TreeMap in Java With Examples
  6. Count Number of Words in a String Java Program
  7. Spring Component Scan Example
  8. Benefits, Disadvantages And Limitations of Autowiring in Spring

Wednesday, April 27, 2022

Comparing Two Strings in Python

For comparing two strings in Python you can use relational operators (==, <, <=, >, >=, !=). Using these operators content of the Strings is compared in lexicographical order and boolean value true or false is returned.

Note that for equality comparison use ‘==’ not 'is' operator as 'is' operator does the identity comparison (compares the memory location of the String objects).

Python String comparison

When Strings are compared in Python, comparison is done character by character.

Checking for equality using ‘==’

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is ',str)
  if str == str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output

String is Python
Strings are equal

In the example using Python string slicing, a slice of the string is obtained which is then compared with another string for equality.

If you use ‘is’ operator, comparison returns false even if the content is same as in that case memory location of the objects is compared.

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is', str)
  if str is str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output


String is Python
Strings are not equal

Python String comparison examples

Let’s see another example with other operators.

def check_equality(str1, str2):
  if str1 > str2:
    print(str1, 'is greater than', str2)

  if str1 < str2:
    print(str1, 'is less than', str2)

  if str1 != str2:
    print(str1, 'is not equal to', str2)

str1 = "This"
str2 = "That"
check_equality(str1, str2)

Output

This is greater than That
This is not equal to That

In the example following condition

if str1 < str2:
  print(str1, 'is less than', str2)

returns false so the message accompanying this condition is not displayed.

That's all for this topic Comparing Two Strings in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Reverse a String
  4. Nonlocal Keyword in Python With Examples
  5. Method Overriding in Python

You may also like-

  1. Name Mangling in Python
  2. Python for Loop With Examples
  3. self in Python
  4. Named Tuple in Python
  5. Switch Case Statement in Java With Examples
  6. Linear Search (Sequential Search) Java Program
  7. Dependency Injection in Spring Framework
  8. Difference Between @Controller And @RestController Annotations in Spring

Wednesday, July 1, 2020

Python String replace() Method

Python String replace() method is used to replace occurrences of the specified substring with the new substring.

Syntax of replace() method

Syntax of replace() method is-

str.replace(old, new, count)

old- Specifies a substring that has to be replaced.

new- Specifies a substring that replaces the old substring.

count- count argument is optional if it is given, only the first count occurrences are replaced. If count is not specified then all the occurrences are replaced.

Return values of the method is a copy of the string with all occurrences of substring old replaced by new.

Replace() method Python examples

1. Replacing specified substring with new value.

def replace_sub(text):
    text = text.replace('30', 'thirty')
    print(text)

replace_sub('His age is 30')

Output

His age is thirty

2. replace() method with count parameter to replace only specified occurrences.

def replace_sub(text):
    text = text.replace('is', 'was')
    print(text)
    # replacing only one occurrence
    print(text.replace('was', 'is', 1))

replace_sub('His age is 30')

Output

Hwas age was 30
His age was 30

3. Replacing character with space.

def replace_sub(text):
    text = text.replace('H', '')
    print(text)

replace_sub('His age is 30')

Output

is age is 30

That's all for this topic Python String replace() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. String Slicing in Python
  3. Python String isdigit() Method
  4. Python String isnumeric() Method
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Installing Anaconda Distribution On Windows
  3. Python while Loop With Examples
  4. Multiple Inheritance in Python
  5. BigDecimal in Java
  6. Java Stream API Tutorial
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Saturday, February 22, 2020

Python String isnumeric() Method

The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not.

isnumeric() method returns true if all characters in the string are numeric characters and there is at least one character, false otherwise. Numeric characters include digits (0..9) and all characters that have the Unicode numeric value property like superscripts or subscripts (as example 26 and 42), fractions like ¼.

Python isnumeric method examples

1. Using isnumeric() method to check if all the characters are digits or not.

str = '345'
print(str)
print(str.isnumeric())

str = 'A12B'
print(str)
print(str.isnumeric())

Output

345
True
A12B
False

2. Using isnumeric() method with superscripts or subscripts. For such strings isnumeric() method returns true.

str = '2\u2076'
print(str)
print(str.isnumeric())

str = '4\u2082'
print(str)
print(str.isnumeric())

Output

26
True
42
True

3. Using isnumeric() method with characters that have Unicode numeric value property.

s = '\u246D' #CIRCLED NUMBER FOURTEEN ?
print(s)
print(s.isnumeric())

s = '\u2474' #PARENTHESIZED DIGIT ONE ?
print(s)
print(s.isnumeric())

s = '\u248C' # DIGIT FIVE FULL STOP ?
print(s)
print(s.isnumeric())

s = '\u24B0' #PARENTHESIZED LATIN SMALL LETTER U ?
print(s)
print(s.isnumeric())

Output

⑭
True
⑴
True
⒌
True
⒰
False

That's all for this topic Python String isnumeric() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String isdigit() Method
  2. Changing String Case in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Abstract Class in Python
  5. Global Keyword in Python With Examples

You may also like-

  1. Python assert Statement
  2. Interface in Python
  3. Python Exception Handling - try,except,finally
  4. Convert String to int in Python
  5. Java Multithreading Tutorial
  6. String in Java Tutorial
  7. Spring Web MVC Tutorial
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Thursday, February 20, 2020

Python String isdigit() Method

The isdigit() method in Python String class is used to check if all the characters in the string are digits or not.

isdigit() method returns true if all characters in the string are digits and there is at least one character, false otherwise. This method works for only positive, unsigned integers and for superscripts or subscripts which are passed as unicode character.

Python isdigit method examples

1. Using isdigit() method to check if all the characters are digits or not.

str = '456'
print(str)
print(str.isdigit())

str = 'A12'
print(str)
print(str.isdigit())

Output

456
True
A12
False

2. Using isdigit() method with superscripts or subscripts. For such strings isdigit() method returns true.

str = '2\u2076'
print(str)
print(str.isdigit())

str = '4\u2082'
print(str)
print(str.isdigit())

Output

26
True
42
True

3. Using isdigit() method with negative numbers or decimal numbers. For such strings isdigit() method returns false.

str = '2.45'
print(str)
print(str.isdigit())

str = '-12'
print(str)
print(str.isdigit())

Output

2.45
False
-12
False

4- To check negative numbers or decimal numbers using Python isdigit() method, you need to remove the minus or a decimal character before checking.

Using lstrip() method you can remove the specified leading characters (used to remove ‘-’ sign here).

Using replace() method you can replace decimal character (replace decimal with no space here).

str = '-12'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '2.45'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '-0.657'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

Output

True
-12
True
2.45
True
-0.657

Since String is immutable in Python so the original string remains unchanged.

That's all for this topic Python String isdigit() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. Python String join() Method
  4. Namespace And Variable Scope in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Python Program to Find Factorial of a Number
  2. Operator Overloading in Python
  3. Abstraction in Python
  4. Volatile Keyword in Java With Examples
  5. Invoke Method at Runtime Using Java Reflection API
  6. Setting And Getting Thread Name And Thread ID - Java Program
  7. Dependency Injection Using factory-method in Spring
  8. HDFS Commands Reference List

Wednesday, February 19, 2020

Check String Empty or Not in Python

If you need to check if a String is empty or not in Python then you have the following options.

Using len() function to check if String is empty

You can check length of String in Python using len() function. If String is of length zero that means it is an empty string. Here note that String with only whitespaces is considered a non-zero length string, if you want to evaluate such string also as empty string then use strip() method to strip spaces before checking the length of the String.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3

As you can see str2 which is a String with whitespaces is not a length zero String so not considered empty. You need to strip whitespaces for such strings.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string.strip()) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3
empty String

Using not to check if String is empty

An empty String is considered false in boolean context so using not string you can find whether the String is empty or not. Here note that String with only whitespaces is not considered false so you need to strip whitespaces before testing for such strings.

def check_if_empty(string):
  if not string.strip():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

empty String
empty String

Using not with str.isspace() method

An empty String is considered false in boolean context and str.isspace() method returns true if there are only whitespace characters in the string and there is at least one character. Using str.isspace() method to check for strings having only whitespaces and not keyword to check for empty strings you can create a condition to check for empty strings including those strings which have only whitespaces.

def check_if_empty(string):
  if not string or string.isspace():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)
str3 = "netjs"
check_if_empty(str3)

Output

empty String
empty String

As you can see both str1 and str2 are considered empty strings.

That's all for this topic Check String Empty or Not in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String join() Method
  2. Getting Substring in Python String
  3. Python continue Statement With Examples
  4. Class And Object in Python
  5. Name Mangling in Python

You may also like-

  1. Interface in Python
  2. Magic Methods in Python With Examples
  3. List Comprehension in Python With Examples
  4. Binary Tree Implementation in Java - Insertion, Traversal And Search
  5. Java Collections Interview Questions And Answers
  6. Difference Between equals() Method And equality Operator == in Java
  7. Using component-scan in Spring to Automatically Discover Bean
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Tuesday, February 18, 2020

Python String join() Method

If you want to join a sequence of Strings in Python that can be done using join() method. Python join() method returns a string which is created by concatenating all the elements in an iterable.

join() method syntax

str.join(iterable)

Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.

str represents a separator that is used between the elements of iterable while joining them.

All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.

Python join() method examples

1. join method with a tuple.

cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)

Output

Chicago:Los Angeles:Seattle:Austin

2. Python join() method with a list of strings.

cities = ['Chicago','Los Angeles','Seattle','Austin']
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

Chicago|Los Angeles|Seattle|Austin

3. TypeError if non-string instance is found.

cities = ['Chicago','Los Angeles','Seattle','Austin', 3]
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

    city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found

In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.

4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.

cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

Austin-Los Angeles-Chicago-Seattle

5. join() method with a Dictionary. In case of dictionary keys are joined not the values.

cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

1-2-3-4

That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce

Sunday, February 16, 2020

Python String split() Method

If you want to split a String in Python that can be done using split() method. Python split() method returns a list of the words in the string, using specified separator as the delimiter, whitespaces are used a separator by default.

split() method syntax

str.split(separator, maxsplit)

Both of the parameters are optional.

separator is the delimiter for splitting a String. If separator is not specified then whitespace is used as separator by default.

maxsplit- Parameter maxsplit specifies the maximum number of splits that are done. If maxsplit is not specified or -1, then there is no limit on the number of splits.

There is also rsplit() method in Python which is similar to split() except for the maxsplit. In case maxsplit is specified in rsplit() method maxsplit splits are done from the rightmost side.

Python split() method examples

1. Using the split method with default parameters (not passing any parameter explicitly).

s = "This is a    test   String"
#break String on spaces
list = s.split()
print(list)

Output

['This', 'is', 'a', 'test', 'String']

Since no parameter is passed with split() method so whitespace is used as separator. Note that runs of consecutive whitespace are regarded as a single separator when default is used.

2. Split string on comma (,) or pipe symbol (|).

s = "Chicago,Los Angeles,Seattle,Austin"
#break String on ,
list = s.split(',')
print(list)

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|')
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle', 'Austin']
['Chicago', 'Los Angeles', 'Seattle', 'Austin']

3. Split string on backslash (\) symbol. With backslash it is better to use escape sequence (\\).

s = "c:\\users\\netjs\\python"
#break String on ,
list = s.split('\\')
print(list)

Output

['c:', 'users', 'netjs', 'python']

4. Limiting the splits using maxsplit parameter. Here split is done for max 2 items.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|', 2)
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle|Austin']

5. Using rsplit() method.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.rsplit('|', 2)
print(list)

Output

['Chicago|Los Angeles', 'Seattle', 'Austin']

That's all for this topic Python String split() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Changing String Case in Python
  2. Python count() method - Counting Substrings
  3. Python Program to Reverse a String
  4. Operator Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. self in Python
  3. Namespace And Variable Scope in Python
  4. raise Statement in Python Exception Handling
  5. PermGen Space Removal in Java 8
  6. String join() Method And StringJoiner Class in Java
  7. Spring Web MVC Java Configuration Example
  8. Data Compression in Hadoop

Saturday, February 15, 2020

Changing String Case in Python

In this tutorial we’ll go through all the methods which are used for changing string case in Python.

In Python there are various methods for changing case of String and also for checking if String is lower case, upper case etc.

Summary of the methods for changing String case in Python

  1. str.lower()- Return a copy of the string with all the cased characters converted to lowercase.
  2. str.upper()- Return a copy of the string with all the cased characters converted to uppercase.
  3. str.capitalize()- Return a copy of the string with its first character capitalized and the rest lowercased.
  4. str.title()- Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

There there are also methods to check the String case, these methods can be used to verify if changing case is really required or not.

  1. str.islower()- Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
  2. str.isupper()- Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
  3. str.istitle()- Return true if the string is a titlecased string and there is at least one character.

Changing String case in Python examples

1. Changing String to all lower case or to all upper case.

s = "This is a TEST String"
print('String in all lower case-',s.lower())
s = "This is a Test String"
print('String in all upper case-', s.upper())

Output

String in all lower case- this is a test string
String in all upper case- THIS IS A TEST STRING

2. Capitalizing the String. First character will be capitalized, if there is any other upper case character in the String that is lower cased.

s = "this is a TEST String"
print('String Capitalized-',s.capitalize())

Output

String Capitalized- This is a test string

3. String title cased. Using title() method you can title cased a String. This method capitalizes the first character of every word.

s = "this is a TEST String"
print('String Title cased-',s.title())

Output

String Title cased- This Is A Test String

4. Checking the case before changing. You can also check the case before changing the case of the String and change the case only if needed. This is an optimization because any String modification method results in a creation of a new String as String is immutable in Python.

s = "this is a test string"
#change only if not already in lower case
if not s.islower():
    s = s.lower()
else:
    print('String already in lower case')
print(s)

Output

String already in lower case
this is a test string
s = "This is a test String"
#change only if not already in upper case
if not s.isupper():
    s = s.upper()
else:
    print('String already in upper case')
print(s)

Output

THIS IS A TEST STRING

That's all for this topic Changing String Case in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Getting Substring in Python String
  2. String Slicing in Python
  3. String Length in Python - len() Function
  4. Convert String to float in Python
  5. Python Program to Check Armstrong Number

You may also like-

  1. Python continue Statement With Examples
  2. Encapsulation in Python
  3. Class And Object in Python
  4. List in Python With Examples
  5. Just In Time Compiler (JIT) in Java
  6. Bucket Sort Program in Java
  7. Spring MVC Exception Handling Tutorial
  8. What is Hadoop Distributed File System (HDFS)

Friday, February 14, 2020

Getting Substring in Python String

In this post we’ll see how to get a substring from a string in Python. Driven by habit most of the developers look for a method in the str class for getting a substring but in Python there is no such method. Getting a substring from a string is done through String slicing in Python.

Format of String slicing is as follows-

Stringname[start_position: end_position: increment_step]

start_position is the index from which the string slicing starts, start_position is included.

end_position is the index at which the string slicing ends, end_position is excluded.

increment_step indicates the step size. For example if step is given as 2 then every alternate character from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at string_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

Getting substring through Python string slicing examples

1. A simple example where substring from index 2..3 is required.

s = "Test String"
print(s[2: 4: 1])
st

Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.

2. Access only the month part from a date in dd/mm/yyyy format. In this case you can use find method to specify the start and end positions for getting a substring.

s = "18/07/2019"
month = s[s.find("/")+1: s.rfind("/") : 1]
print('Month part of the date is-', month)
Month part of the date is- 07

That's all for this topic Getting Substring in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Accessing Characters in Python String
  2. Python count() method - Counting Substrings
  3. Comparing Two Strings in Python
  4. Convert String to int in Python
  5. Functions in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. self in Python
  3. Polymorphism in Python
  4. Python while Loop With Examples
  5. Zipping Files And Folders in Java
  6. Java Collections Interview Questions And Answers
  7. Spring Object XML Mapping (OXM) JAXB Example
  8. How to Create Ubuntu Bootable USB

Thursday, February 13, 2020

Python count() method - Counting Substrings

If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that.

Format of the count() method in Python is as follows-

str.count(sub, start, end)

Here sub is the substring which has to be counted in the String str. Parameters start and end are optional, if provided occurrences of substring would be counted with in that range otherwise whole string length is taken as range.

Python string count() method example

1. Using count() method with no start and end parameters.

s = "This a test string to test count method"
print('Count-', s.count("test"))

Output

Count- 2

2. Using count() method with start and end parameters.

s = "This a test string to test count method"
# passing range for search 
count = s.count("test", s.find("test"), s.rfind("test"))
print('Count-', count)

Output

Count- 1

In the example range for search is passed using find() and rfind() methods, where find() returns the lowest index in the string where substring is found and rfind() returns the highest index in the string where substring sub is found.

3. Calculating count of character ‘o’ in the String.

s = "This a test string to test count method"
count = s.count("o")
print('Count-', count)

Output

Count- 3

That's all for this topic Python count() method - Counting Substrings. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Count Number of Words in a String
  4. Passing Object of The Class as Parameter in Python
  5. raise Statement in Python Exception Handling

You may also like-

  1. Python return Statement With Examples
  2. Global Keyword in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Program to Display Prime Numbers
  5. final Keyword in Java With Examples
  6. Binary Tree Traversal Using Depth First Search Java Program
  7. Spring Profiles With Examples
  8. Input Splits in Hadoop

Wednesday, February 12, 2020

Accessing Characters in Python String

Python String is an ordered sequence of characters and stored as an array. In order to access characters in a String you need to specify string name followed by index in the square brackets. Note that index is 0 based and valid range for string of length n is 0..(n-1).

In String in Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

Accessing characters from String in Python

Getting characters from a string in Python example

s = "Hello World"
#first character
print(s[0])
#3rd character
print(s[2])
print('length of String', len(s))
#last character
print(s[len(s)-1])

Output

H
l
length of String 11
d

Getting characters using negative indexing

s = "Hello World"
# last character
print(s[-1])
print('length of String', len(s))
# first character by making the index negative
print(s[-(len(s))])

Output

d
length of String 11
H

That's all for this topic Accessing Characters in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. String Length in Python - len() Function
  4. Python while Loop With Examples
  5. Multiple Inheritance in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Python Program to Find Factorial of a Number
  3. Python Functions : Returning Multiple Values
  4. Tuple in Python With Examples
  5. BigDecimal in Java
  6. Java ThreadLocal Class With Examples
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Tuesday, February 11, 2020

Removing Spaces From String in Python

If you have to remove spaces from a string in Python you can use one of the following options based on whether you want to remove leading spaces, trailing spaces, spaces from both ends or spaces in between the words too.

  • str.lstrip()- Using this method you can remove the leading whitespaces from a String. See example.
  • str.rstrip()- using this Python String method you can remove the trailing whitespaces from a String. See example.
  • str.strip()- This method helps in removing both leading and trailing whitespaces from a String in Python. See example.
  • re.sub()- By using re (Regular Expression) module's re.sub() function and passing the regular expression for spaces and replacement as a single space you can remove spaces in between words too apart from both leading and trailing whitespaces. See example.

Note that String is immutable in Python so these methods return a new copy of the String which has to be assigned to a String to store the new reference, otherwise the modified string is lost.

lstrip() - Removing leading whitepaces from String in Python

To remove spaces from the start of the String lstrip() method can be used.

string = "    String with leading spaces"
print(string)
print(string.lstrip())

Output

    String with leading spaces
String with leading spaces

rstrip() - Removing trailing whitepaces from String in Python

To remove spaces from the end of the String rstrip() method can be used.

string = "String with trailing spaces    "
print(string)
print(string.rstrip())

Output

String with trailing spaces     
String with trailing spaces

strip() - Removing both leading and trailing whitespaces from String in Python

To remove spaces from both start and end of the String strip() method can be used.

string = "       String with leading and trailing spaces    "
print(string)
print(string.strip())

Output

       String with leading and trailing spaces    
String with leading and trailing spaces

Using re.sub() function in Python

You need to import re module to use this function. Function re.sub() replaces one or many matches with a replacement string.

In the function “//s+” is passed as a regular expression to match any number of spaces. As a replacement for those matches you can pass “” when removing leading and trailing spaces and a single space (“ ”) when removing spaces in between words.

^- represents start of the String

$- represents end of the String

string = "       String with    leading and    trailing spaces    "
print(string)
# removing leading and trailing spaces
string = re.sub("^\\s+|\\s+$", "", string)
# replacing more than one space between words with single space
string = re.sub("\\s+", " ", string)
print(string)

Output

       String with    leading and    trailing spaces    
String with leading and trailing spaces

That's all for this topic Removing Spaces From String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Comparing Two Strings in Python
  2. String Slicing in Python
  3. Getting Substring in Python String
  4. Operator Overloading in Python
  5. Polymorphism in Python

You may also like-

  1. Class And Object in Python
  2. pass Statement in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Python Exception Handling - try,except,finally
  5. Conditional Operators in Java
  6. HashSet in Java With Examples
  7. Race Condition in Java Multi-Threading
  8. Different Bean Scopes in Spring