Tuesday, 30 May 2023

Replace all the occurrences of sub string in the given string

Using string.replace() method, we can replace all the matching substrings in a string.

 

replace_sub_string.py

str1 = 'hello there, hi there'

str2 = str1.replace('there', 'Krishna')

print('str1 : ', str1)
print('str2 : ', str2)

 Above snippet generate below output.

str1 :  hello there, hi there
str2 :  hello Krishna, hi Krishna

 


  

Previous                                                 Next                                                 Home

Python: Get number of characters in a String

Using python built-in function ‘len()’, we can get the number of characters in a string.

 

no_of_chars_in_string.py

str = 'Hello World'
msg = f'"{str}" has {len(str)} characters'

print(msg)

 

Output

"Hello World" has 11 characters

 

 

 

 

Previous                                                 Next                                                 Home

Formatted strings in Python

Formatted strings in Python provide a way to evaluate the expressions in a String. Formatted strings are defined with prefix 'f', followed by a string that contain some placeholders to replace the expression values at runtime. Find the below example.

 

formatted_strings_1.py

name = 'Krishna'
age = 35
country = 'India'

msg = f'I am {name} from {country}, and I am {age} years old'
print(msg)

 


In this example, the formatted string f'I am {name} from {country}, and I am {age} years old' is used to create a formatted string. The expressions within curly braces ({}) are evaluated and their values are inserted into the string at those positions. The variables name, age and country are formatted and placed within the string, resulting in the desired output.

Above program generates below output.

I am Krishna from India, and I am 35 years old

Formatted strings support Format specifiers

Formatted strings support various format specifiers to specify the presentation of values like decimal places, padding, alignment etc.,

 

Alignment and padding example

name = 'Krishna'
age = 35
country = 'India'
msg = f'name : {name:<15}, age : {age:03}, country : {country:>10}.'

‘:’ is followed by a format specifier inside the curly braces {} within the f-string ‘msg’ to specify padding and alignment.

 

a.   < is used for left alignment.

b.   15 specifies the width of the field, indicating that the name should occupy 15 characters.

c.    03 specifies the width of the field is 3 characters and pad the age value with leading zeros if needed.

d.   > is used for right alignment

e.   10 specifies the width of the field, indicating that the country should occupy 10 characters.

 

Output

name : Krishna        , age : 035, country :      India.

Decimal places example

pi = 3.1415714285
formatted_pi = f"pi = {pi:.4f}" #3.1416

In this example, pi is formatted with :.4f, which specifies that it should be displayed with four decimal places.

 

Format numeric values with a comma (,)

n = 123456789.987654
formatted_n = f"n = {n:,f}" #123,456,789.987654

In the above example, I used the format specifier ‘:,f’ to format the decimal value with a comma (,).

 

We can even restrict number of decimal places with the format specifier ':,.3f', which restrict number of decimal places to 3.

 

Display a decimal number to binary, ocatal and hexa

n = 23
binary = f"Binary: {n:b}" #Binary: 10111
octal = f"Octal: {n:o}" #Octal: 27
hexadecimal = f"Hexadecimal: {n:x}" #Hexadecimal: 17

In the above example, I used the format specifiers :b, :o, and :x to display the number in binary, octal, and hexadecimal.

 

Format date and time

now = datetime.now()
formatted_date_and_time = f"date and time: {now:%Y-%m-%d %H:%M:%S}" #date and time: 2023-05-30 12:47:56

In the above example, I used the format specifier ‘:%Y-%m-%d %H:%M:%S’ to format today’s datetime.

 

Find the below working application.

 

formatted_strings_with_format_specifiers.py

from datetime import datetime

print('Alignment and padding example')
name = 'Krishna'
age = 35
country = 'India'
msg = f'name : {name:<15}, age : {age:03}, country : {country:>10}.'
print(msg)

print('\nDecimal places example')
pi = 3.1415714285
formatted_pi = f"pi = {pi:.4f}"
print('pi : ', pi)
print('formatted_pi : ', formatted_pi)

print('\nFormat numeric values with a ,')
n = 123456789.987654
formatted_n = f"n = {n:,f}"
print('n : ', n)
print('formatted_n : ', formatted_n)

print('\nFormat numeric values with a , and restrict decimal places to 3')
formatted_n = f"n = {n:,.3f}"
print('formatted_n : ', formatted_n)

print('\nFormat a decimal number to binary, ocatal and hexa')
n = 23
binary = f"Binary: {n:b}"
octal = f"Octal: {n:o}"
hexadecimal = f"Hexadecimal: {n:x}"
print('n : ', n)
print(binary)
print(octal)
print(hexadecimal)

print('\nFormat date and time')
now = datetime.now()
formatted_date_and_time = f"date and time: {now:%Y-%m-%d %H:%M:%S}"
print(formatted_date_and_time)

Output

Alignment and padding example
name : Krishna        , age : 035, country :      India.

Decimal places example
pi :  3.1415714285
formatted_pi :  pi = 3.1416

Format numeric values with a ,
n :  123456789.987654
formatted_n :  n = 123,456,789.987654

Format numeric values with a , and restrict decimal places to 3
formatted_n :  n = 123,456,789.988

Format a decimal number to binary, ocatal and hexa
n :  23
Binary: 10111
Octal: 27
Hexadecimal: 17

Format date and time
date and time: 2023-05-30 12:47:56

References

https://docs.python.org/3/library/string.html#formatspec

 

 

 

Previous                                                 Next                                                 Home

Monday, 29 May 2023

Micronaut: rest: Hello world application

Simple controller snippet in Micronaut looks like below.

@Controller("/welcome")
public class WelcomeController {

	@Get(produces = MediaType.TEXT_PLAIN)
	public String index() {
		return "Welcome to Micronaut app!!!!";
	}
}

 

a.   The class is defined as a controller with the @Controller annotation mapped to the path /welcome

b.   The method responds to a GET requests to /welcome and returns a response with a text/plain content type

 

To run the application in embedding server, use below snippet.

public class App {

	public static void main(String[] args) {
		Micronaut.run(App.class);
	}
}

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-rest-hello-world’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-rest-hello-world</artifactId>
	<version>0.1</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>io.micronaut</groupId>
		<artifactId>micronaut-parent</artifactId>
		<version>3.7.3</version>
	</parent>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>11</jdk.version>
		<release.version>11</release.version>
		<micronaut.version>3.7.3</micronaut.version>
		<micronaut.runtime>netty</micronaut.runtime>
		<exec.mainClass>com.sample.app.App</exec.mainClass>
	</properties>

	<repositories>
		<repository>
			<id>central</id>
			<url>https://repo.maven.apache.org/maven2</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-validation</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-client</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-server-netty</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-jackson-databind</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>jakarta.annotation</groupId>
			<artifactId>jakarta.annotation-api</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut.test</groupId>
			<artifactId>micronaut-test-junit5</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>io.micronaut.build</groupId>
				<artifactId>micronaut-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<!-- Uncomment to enable incremental compilation -->
					<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->

					<annotationProcessorPaths
						combine.children="append">
						<path>
							<groupId>io.micronaut</groupId>
							<artifactId>micronaut-http-validation</artifactId>
							<version>${micronaut.version}</version>
						</path>
					</annotationProcessorPaths>

				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Step 3: Define WelcomeController class.

 

WelcomeController.java

package com.sample.app.controller;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/welcome")
public class WelcomeController {

	@Get(produces = MediaType.TEXT_PLAIN)
	public String index() {
		return "Welcome to Micronaut app!!!!";
	}
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import io.micronaut.runtime.Micronaut;

public class App {

	public static void main(String[] args) {
		Micronaut.run(App.class);
	}
}

Total project structure looks like below.




Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

Upon command successful execution, you can see the jar file ‘micronaut-rest-hello-world-0.1.jar’ in project target folder.

$ls ./target/
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-rest-hello-world-0.1.jar
original-micronaut-rest-hello-world-0.1.jar
test-classes

 

Execute below command to run the application.

java -jar ./target/micronaut-rest-hello-world-0.1.jar

 

Once the application started, open the url ‘http://localhost:8080/welcome’ in browser, you will see below kind of screen.

 


 

You can download the application from this link.

 

Let’s learn, how to test the hello-world application in the next post.


 

Previous                                                    Next                                                    Home