Sunday, March 22, 2026

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

Accessing Characters in Python String

Python String is an ordered sequence of unicode 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. Since Python uses zero-based indexing, the first character of a string is at position 0, and for a string of length n, valid indices range from 0 to n-1.

In String in Python you can also use negative indexing which allows you to access characters starting from the end of the string. For example, -1 refers to the last character, -2 to the second last, and so on.

Here is an illustration of accessing characters in a Python string using both positive (left to right) and negative (right to left) indexing.

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

Saturday, March 21, 2026

Removing Spaces From String in Python

Removing spaces from string in Python is a common task when cleaning or formatting text data. Python provides several built-in string methods that make this process simple and efficient. Depending on whether you want to remove leading spaces, trailing spaces, both ends, or even spaces inside the string, you can choose from the following options:

  • 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.

It’s important to note that strings in Python are immutable, meaning these methods return a new string rather than modifying the original one. To keep the modified version, you must assign the result to a variable.

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

Thursday, March 19, 2026

Python count() method - Counting Substrings

If you want to count the number of occurrences of a specific substring in a string in Python, the most efficient way is to use the built-in count() method.

The general syntax of the Python count() method is as follows-

str.count(sub, start, end)

Parameters:

  • sub- The substring you want to count in the String str.
  • start (optional)- The starting index of the search range.
  • end (optional)- The ending index of the search range.

If start and end are not provided, Python counts occurrences across the entire string. When they are specified, only the substring occurrences within that slice are counted.

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, 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

How ArrayList Works Internally in Java

When it comes to Java Collections, ArrayList stands alongside HashMap as one of the most widely used data structures. In fact, most Java developers rely on ArrayList almost daily to store and manage objects efficiently. Earlier, I explained how HashMap works internally in Java; in this article, we’ll dive deep into how ArrayList works internally in Java, a topic that frequently appears in interviews and is crucial for mastering the Collections Framework.

At its core, ArrayList is a resizable-array implementation of the List interface. Unlike a traditional array, which has a fixed size, ArrayList can grow dynamically as elements are added. This flexibility is achieved through an internal mechanism that ensures there’s always room for new elements without manual resizing.

So, let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.

Because of all these side questions it is also a very important Java Collections interview question.

Note that the code of ArrayList used here for reference is from Java 25


Where does ArrayList internally store elements

Backing data structure used by Java ArrayList to store its elements is an array of Object class, which is defined as follows-

transient Object[] elementData;

This elementData array is where all objects are actually stored. The keyword transient is important here: it tells the JVM not to serialize this field by default. You might wonder, if the core storage is transient, how does serialization of an ArrayList still work? The answer lies in the fact that ArrayList overrides the writeObject and readObject methods. These custom implementations ensure that the contents of elementData are properly serialized and deserialized, even though the field itself is marked transient.

Wednesday, March 18, 2026

Getting Substring in Python String

When it comes to getting substring in Python string, many developers instinctively look for a built-in substring() method, as found in other languages. However, Python takes a different approach, there is no dedicated method for substrings. Instead, Python uses the powerful concept of string slicing, which is both flexible and concise.

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 three parameters are optional-

  • If start_position is omitted, slicing starts from index 0.
  • If end_position is omitted, slicing continues to the last character.
  • If step is omitted, the default is 1.

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. Python makes this simple using string slicing combined with the find() method.

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

Is String Thread Safe in Java

We do know that String objects are immutable. It is also true that immutable objects are thread-safe so by transitive law string objects are thread-safe. So, if you are asked the question "Is String Thread Safe in Java?", the short answer is yes.

But let’s go deeper into why this holds true. To understand whether String in Java is thread-safe, we first need to break down two key concepts: immutability and thread safety.

Immutable object- An immutable object is one whose state cannot be modified after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.

Thread safety– I’ll quote "Java concurrency in practice" book here– "A class is thread-safe if it behaves correctly when accessed from multiple threads, where correctness means that a class conforms to its specification".

Thread safety in String

String in Java, being immutable, has the specification that its values are constant and cannot be changed once created.

But there is a little confusion with many users when it comes to this question Is String thread safe in Java. Many people think that string is immutable so thread safety here should mean even if multiple threads are accessing the same string those threads should not be able to change the content of the string at all as the String being immutable can't be modified.

In reality, immutability ensures that no thread can ever change the content of an existing String. Any operation that appears to modify a String—such as concatenation, replacement, or substring- actually creates a new String object. The reference is updated to point to this new object, while the original remains unchanged.

So even in a multi-threaded environment, if several threads are working with the same String, they are all safely accessing an immutable value. If one thread performs an operation that "changes" the string, it simply receives a new reference, leaving the original untouched. This behavior guarantees that String in Java is inherently thread-safe.

Java String thread safe example

Let’s try to see this with an example. In this example three threads are created and all of them share the same string object. In each of these thread, thread name is appended to the string and then that string is printed. Thread class' join() method is also used here to wait for all of the threads to finish and then the string object is printed again.

public class StrThread implements Runnable {
  private String s;
  //Constructor
  public StrThread(String s){
    this.s = s;
  }
  @Override
  public void run() {
    System.out.println("in run method " + Thread.currentThread().getName());        
        
    try {
      // introducing some delay
      Thread.sleep(50);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }  
    // Adding to String  
    s = s + Thread.currentThread().getName();
    System.out.println("String " + s);
  }
    
  public static void main(String[] args) {
    String str = "abc";
    // Three threadss
    Thread t1 = new Thread(new StrThread(str));
    Thread t2 = new Thread(new StrThread(str));
    Thread t3 = new Thread(new StrThread(str));
    t1.start();
    t2.start();
    t3.start();
    // Waiting for all of them to finish
    try {
      t1.join();
      t2.join();
      t3.join();
    } catch (InterruptedException e) {    
      e.printStackTrace();
    }
    System.out.println("String is " + str.toString());
  }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-1
String abcThread-2
String abcThread-0
String is abc

Here note that every thread changes the content of the string but in the process where str refers to is also changed, so effectively each thread gets its own string object. Once all the threads finish, str is printed in the main method again and it can be seen that the original string's value remains unchanged meaning original reference with the original content remains intact.

With this program you can see that String is immutable so original String won't be changed but String reference can still be changed with multiple threads. So Java Strings are thread safe here means when the shared String is changed it creates a new copy for another thread that way original String remains unchanged.

To see what may happen with a mutable object let us use StringBuffer in the place of String.

public class StrThread implements Runnable {
  private StringBuffer s;
  //Constructor
  public StrThread(StringBuffer s){
    this.s = s;
  }
  @Override
  public void run() {
    System.out.println("in run method " + Thread.currentThread().getName());        
      
    try {
      // introducing some delay
      Thread.sleep(50);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }    
    s.append(Thread.currentThread().getName());
    System.out.println("String " + s);
  }
    
  public static void main(String[] args) {
    StringBuffer str = new StringBuffer("abc");
    // Three threadss
    Thread t1 = new Thread(new StrThread(str));
    Thread t2 = new Thread(new StrThread(str));
    Thread t3 = new Thread(new StrThread(str));
    t1.start();
    t2.start();
    t3.start();
    // Waiting for all of them to finish
    try {
      t1.join();
      t2.join();
      t3.join();
    } catch (InterruptedException e) {    
      e.printStackTrace();
    }
    System.out.println("String is " + str.toString());
  }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-0
String abcThread-0Thread-2
String abcThread-0Thread-2Thread-1
String is abcThread-0Thread-2Thread-1

Note– output may vary in different runs

Here it can be seen that shared StringBuffer object is modified.

That's all for this topic Is String Thread Safe in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. String Comparison in Java equals(), compareTo(), startsWith() Methods
  3. Java trim(), strip() - Removing Spaces From String
  4. StringBuilder Class in Java With Examples
  5. Java String Interview Questions And Answers

You may also like-

  1. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  2. Deadlock in Java Multi-Threading
  3. Interface Default Methods in Java
  4. Effectively Final in Java 8
  5. Java BlockingQueue With Examples
  6. Callable and Future in Java With Examples
  7. Access Modifiers in Java - Public, Private, Protected and Default
  8. Try-With-Resources in Java With Examples