Heels of Achilles: About IoT Vulnerabilities

Heels of Achilles: About IoT Vulnerabilities

IoT vulnerabilities

Internet of Things security: Top 10 smart device vulnerabilities

Greetings, dear readers. We recently published an article about IoT testing. And we see how the views of that page are steadily growing. Given your interest in this topic, today we decided to talk about another aspect of it, which was poorly covered in the previous article. These are IoT vulnerabilities. Everything you read below was not invented by us and is only partly based on our own experience, although we have significant experience in this area. Most of the information below is a summary of huge studies, the results of which have been recognized by experts from all over the world. Enjoy reading!

Opening speech

So, you already know that the popularity of “smart” things is steadily growing, and by 2030 IoT will connect more than 25 billion devices around the world, and these are only the most modest forecasts. In this regard, the importance of the issue of IoT weaknesses is increasing. According to a large report published by NetScout in 2018, on average, the first IoT security attack occurs as early as five minutes after a device is connected. And the point here is not that someone is trying to attack you, it’s just that most of the attacks have long been automated, so they “hit” everyone who is in the zone of influence.

It is clear that specialists in cyber security in IoT could not leave this unattended. The most relevant research on this topic is the report of the non-profit organization OWASP from 2018. The publication also talks about the most common IoT device vulnerabilities and security risks. Below we briefly review the top 10 weaknesses discussed in the report.

Achilles the centipede: how to hack your IoT devices

Yes, indeed, today IoT is a many-legged Achilles, but after all, Rome was not built in one day, was it? Letting the future into our present brings us closer to the moment when we don’t have to worry about security at all. Well, in the meantime, you should be careful, but definitely not panic and not deny the existence of the Internet of things as such. So, here’s what you should pay attention to.

IoT security attack

Physical accessibility of devices

And let’s start simple. One of the most commonplace IoT devices security vulnerabilities is the ability to physically get to them. Some devices can be installed outdoors, in crowded places, so it doesn’t cost anything for an attacker to copy the settings (IP network, MAC address, etc.) and replace the original device in order to listen or reduce network performance. It can hack an RFID reader, hack a hardware device, infect it with malware, steal data, or simply physically disable an IoT device.

The solution to this problem is as simple as the problem itself. Care must be taken to ensure that the devices cannot be accessed by anyone who so pleases. For these purposes, there are anti-vandal boxes, for example. And simple installation of devices at an unattainable height can protect you from undesirable consequences. This is clear enough.

Insecure Defaults

Any manufacturer wants to earn more and spend less. Some devices may have a lot of smart features but lack the ability to configure security protocols in IoT.

For example, checking passwords for strength is not supported, there is no possibility to create accounts with different rights (administrator and users), there is no setting for encryption, logging and notifying users about security events.

Inability to control the device

Another IoT security breach is that devices are most often a “black box”. They do not have the ability to monitor the state of work, to identify which services are running and with what they interact.

Not all manufacturers allow users of IoT devices to fully manage the operating system and running applications, as well as check the integrity and legitimacy of downloaded software or install update patches on the OS.

During attacks, the device firmware can be reconfigured so that it can only be repaired by completely flashing the device.

The solution to these problems can be the use of specialized software for managing IoT devices, for example, cloud solutions from AWS, Google, IBM, etc.

Insecure transmission and storage of data

There is also a data breach: IoT devices collect and store environmental data, including various personal information. A compromised password can be replaced, but stolen data from a biometric device (fingerprint, retina, facial biometrics) cannot.

At the same time, IoT devices can not only store data in unencrypted form but also transmit it over the network. If the transmission of data in clear text over a local network can be somehow explained, then in the case of a wireless network or transmission over the Internet, they can become the property of anyone.

The user himself can use secure communication channels to ensure his IoT network security, but the device manufacturer must take care of encrypting stored passwords, biometrics, and other important data.

Insufficient privacy protection

This paragraph echoes the previous one: all personal data must be stored and transmitted in a secure manner. But this paragraph considers privacy in a deeper sense, namely from the point of view of protecting the secrets of private life.

IoT exploits information about what and who surrounds them, including unsuspecting people. Stolen or mishandled user data can both inadvertently discredit a person (for example, when misconfigured traffic cameras exposed unfaithful spouses) or be used in blackmail.

To solve the problem, you need to know exactly what data is collected by the IoT device, mobile application, and cloud interfaces.

You need to make sure that only the data necessary for the operation of the device is collected, check whether there is permission to store personal data and whether it is protected, and whether data storage policies are prescribed. Otherwise, if these conditions are not observed, the user may have problems with the law.

Use of unsafe or obsolete components

The vulnerable IoT devices` components can nullify all configured security.

At the beginning of 2019, expert Paul Marrapese identified vulnerabilities in the iLnkP2P P2P utility, which is installed on more than 2 million devices connected to the network: IP cameras, baby monitors, smart doorbells, video recorders, etc.

The first vulnerability CVE-2019-11219 allows an attacker to identify the device, and the second one, iLnkP2P authentication vulnerability CVE-2019-11220, allows to intercept traffic in the clear, including video streams and passwords.

Over the course of several months, Paul contacted the manufacturer three times and twice the developer of the utility but never received a response from them.

The solution to this problem is to monitor the release of security patches and update the device, and if your IoT devices are unsecured for a long time… change the manufacturer.

Lack of secure update mechanisms

The inability to upgrade a device is itself an IoT weakness. Failure to install the update means devices remain vulnerable indefinitely.

But besides that, the update itself and the firmware can also be unsafe. For example, if you do not use encrypted channels to get the software, the update file is not encrypted or integrity checked before installation, there is no anti-rollback protection (protection against reverting to a previous, more vulnerable version), or there are no notifications about security changes due to updates.

The solution to this problem is also on the side of the manufacturer. But you can check if your device is able to update at all and if it meets the IoT security requirements. Make sure that the update files are downloaded from a trusted server over an encrypted channel and that your device uses a secure update installation architecture.

Insecure ecosystem interfaces

The use of insecure web interfaces, APIs, and cloud or mobile interfaces makes IoT devices vulnerable to compromise even without connecting to them.

For example, Barracuda Labs analyzed the vulnerabilities of IoT application and the web interface of one of the “smart” cameras and found breaches that allow you to get the password to the device:

  • the mobile application ignored the validity of the server certificate;
  • the web application was vulnerable to cross-site scripting;
  • it was possible to bypass files on the cloud server;
  • device updates were not protected;
  • the device was ignoring the validity of the server certificate.

For protection, you need to change the default user and password, and make sure that the web interface is not subject to cross-site scripting, SQL injection, or CSRF attacks. Protection against brute-force attacks on passwords should also be implemented. For example, after three attempts to enter an incorrect password, the account should be blocked and allow password recovery only through a hard reset. This will protect your IoT device from attacks of malicious.

Weak or guessable password

Surprisingly, even in 2022, the biggest breach in security for IoT is created by users themselves, using weak, default, or leaked passwords.

Despite the obvious need for a strong password, some users still do not change their default passwords. Silex malware took advantage of this in June 2019, turning about 2,000 IoT devices into a “brick” within one hour.

And before that, the well-known botnet and Mirai worm managed to infect 600,000 IoT devices using a database of 61 standard login-password combinations.

The solution is to change your password!

IoT devices security

Conclusion

As you can see, some of the internet of things vulnerabilities are quite simply solved by ordinary care when connecting or installing devices (physical). Of course, there are security vulnerabilities that can be found in the IoT devices themselves. Such problems are most often solved by updating or changing the manufacturer. This is about the end user.

In this regard, the requirements for the manufacturer and software developers are much higher. However, so far, they are not regulated by law, which means that not all manufacturers will be willing to spend more to make the device safer, unfortunately. The only way for a buyer to influence the industry is not to buy vulnerable IoT devices.

Cassandra vs Dynamodb – Which Side Is The Engineer On?

Cassandra vs Dynamodb – Which Side Is The Engineer On?

Cassandra vs DynamoDB

Cassandra vs DynamoDB differences and purpose. How to make the right choice?

In this article, we will look at two progressive and scalable databases – Cassandra and DynamoDB. At the time of modeling, developers are faced with the task of choosing the optimal database management system to maximize the needs of a particular project. Also, an important point is the scalability and security of data storage. You should also not forget about fault tolerance, because no one is immune from external factors. And when the question of choosing which database to use is brewing, then you need to describe and compare the main features in order to choose the best option. Consider the database data.

What is Cassandra used for?

Apache Cassandra is an open-source columnar database model. The main design intent was to store and process large data sets with a minimum response time when receiving and changing records. Cassandra database also has a well-developed level of fault tolerance and high scalability, which makes it possible to use this database in several data centers at the same time. In Cassandra, when writing large amounts of data, the reading speed does not decrease, which makes it competitive in the IT market. It should also be noted that leading companies such as Facebook, Instagram, Twitter, and eBay use Cassandra in their applications.

What is a column model?

A columnar model is also called a tabular model. The table contains rows, which in turn contain columns, and in each, row the number of columns may differ. Each column family must have a primary key. The key in this case can be either simple or compound.

If the key is simple, it contains the partition key, which determines which node or partition will store the final data.

If the key is composite, then in this case it includes both the partition key and the clustering columns themselves.

Column database

Cassandra alternatives – what is DynamoDB?

 In turn, DynamoDB is not just a database, it is a managed service provided by Amazon. This service has a number of advantages, such as high throughput, scalability, and support for element-level capture streams. We should not forget about the function of automatic DynamoDB scaling and load balancing, which allows you to ensure high performance even under heavy loads. This DynamoDB database does not need equipment, since all the data is in the cloud, and you also do not need to think about updating the software part, Amazon takes over this task. Also, Amazon provides high-quality security, backup, end-to-end integration with other Amazon services. Automatic replication and no limit on the amount of data.

DynamoDB and Cassandra Database Comparison

Having given the basic data about each database, it should be noted the main pros and cons of each of them.

The main advantages of Cassandra include:

  • Storage of data of any level of structuring.
  • High data download speed, no loss of reading speed.
  • Processing huge amounts of data on multiple servers in parallel.
  • Open-source.
  • Fast system response.

The main advantages of DynamoDB include:

  • Streams for capturing element-level changes.
  • Encryption Data Advanced Encryption Standard (AES-256)
  • Export data to other Amazon services
  • Support for distributed hash tables.
  • No data limit
  • Flexible storage
  • Has fine-grained access control (FGAC)

The main disadvantages of DynamoDB include:

  • Very weak query language model
  • Simultaneous support for tables of only one region
  • Lack of SQL support requests
  • Binding to AWS.

Which database to choose?

Having considered the data on two progressive databases, the question of choosing a specific database for the project becomes. Since we see that there is no ideal database, we will proceed from the purpose for which we create the application. In this case, DynamoDB has proven itself well in IoT content management, or gaming applications where you need to have good logging and fast response speed.

In turn, Cassandra is used in recommendation and personalization systems, messaging due to linear scalability.

Conclusions

Cassandra databases and DynamoDB. Each of them had both strengths and weaknesses. The choice of a database for a project in this case is best done based not only on specific needs, but also on the direction in which the database will be used. This will allow you to get maximum speed with high reliability.

What are Async and Await Methods in C# Asynchronous Programming

What are Async and Await Methods in C# Asynchronous Programming

C# Asynchronous programming

C# Asynchronous programming

What is Async?

Async is a C# reference, to indicate that a method, lambda expression, or anonymous method is asynchronous, use the async modifier. A method or expression is referred to as an async method if this modifier is applied to it. The async C# method ExampleMethodAsync is defined in the example that follows:

public async Task<int> ExampleMethodAsync()
{
    //...
}

Read the introduction in Asynchronous programming with async and await if you’re new to asynchronous programming or don’t know how an async method utilizes the await operator to perform potentially lengthy work without blocking the caller’s thread. The HttpClient is called by the code described below, which is contained inside an async method. Method called GetStringAsync:

string contents = await httpClient.GetStringAsync(requestUrl);

Until it encounters its first await statement, an async method executes synchronously. After that, the method is suspended until the task that is being anticipated has finished. Control then passes back to the method’s caller, as demonstrated by the example in the next section.

If an await expression or statement is absent from the method that the async keyword alters, the method operates synchronously. Any async methods without await statements trigger a compiler warning, alerting you to the possibility of an error. Refer to CS4014, Compiler Warning (level 1).

Async is a contextual keyword, meaning it can only be used to modify methods, lambda

C# async and C# await

The async and await keywords in C# help make asynchronous programming highly common these days. The entire application will have to wait to complete the operation when working with UI and using a long-running method that will take a long time, such as reading a huge file, on button click. In other words, if any process in a synchronous application becomes blocked, the entire application also becomes halted, and our application ceases to function until the entire task has been completed.

In this situation, asynchronous programming is highly useful. The application can carry on with tasks that don’t depend on the task’s completion by employing asynchronous programming.

With the aid of the async and await keywords, we will achieve all the advantages of conventional asynchronous programming with a great deal less work.

 

Let’s say we have two methods, Method1 and Method2, that are independent of one another and that Method1 takes a long time to perform its task. Synchronous programming starts with Method1 and waits for it to finish before moving on to Method2, which is then executed. Even if both procedures are independent of one another, the process will take a lot of time.

 

By utilizing simple thread programming, we can run all the functions concurrently, but this would block the user interface while we wait for the tasks to be finished. In traditional programming, we would need to write a lot of code to solve this issue, but if we utilize the async and await keywords, we can solve the issue with a lot less code.

We’ll see other examples as well, and in those cases when Method3 depends on Method1, it will use the await keyword to wait for Method1 to finish running.

In C#, async and await are code markers that indicate where control should return when a task has been completed.

Start by using real-world examples to help you grasp the concept of programming.

Await async: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.

Code exemples on Async await C#:

We are going to use a console application for our demonstration in this case.

 Sample:

class Program
{
static void Main(string[] args)
{
Method1();
Method2();
Console.ReadKey();
}
public static async Task Method1()
{
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
// Do something
Task.Delay(100).Wait();
}
});
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2");
// Do something
Task.Delay(100).Wait();
}
}
}

Method 1 and Method 2 in the code above are independent of one another, and we are calling from the Main method.

Here, it is obvious that Method 1 and Method 2 are not waiting on one another.

Result:

C# async

With regard to the second illustration, let’s say Method 3 is dependent on Method 1.

Example no.2

In this illustration, Method 1 returns the overall length as an integer value, and Method 3 receives a parameter named length that is passed from Method 1 as a value.

Before giving a parameter to Method 3, we must use the await keyword in this case, and to do so, we must use the async keyword from the calling method.

Async cannot be used in the Main method for the console application if C# 7 or below is being used because it will result in the error detailed below.

C# async error

A new method called callMethod will be created, and in this method, all of our methods will be called Method 1, Method 2, and Method 3, correspondingly.

Code Sample in C# no.3:

 callMethod();
Console.ReadKey();
}
public static async void callMethod()
{
Task<int> task = Method1();
Method2();
int count = await task;
Method3(count);
}
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2");
}
}
public static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}

Code Sample in C# no.4:

class Program
{
static void Main(string[] args)
{
class Program
{
static async Task Main(string[] args)
{
await callMethod();
Console.ReadKey();
}
public static async Task callMethod()
{
Method2();
var count = await Method1();
Method3(count);
}
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2");
}
}
public static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}

The return type of Method 1 is the only parameter Method3 in the code above needs. In this case, the await keyword is essential for waiting for Method 1 task completion.

Result:

Async programming sample

Actual instance:

There are a few.NET Framework 4.5 supporting APIs, and the Windows runtime has methods that support async programming.

 

With the aid of the async and await keywords, we can leverage all of these in real-time projects to speed up task completion.

HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder, etc. are a few APIs that include async functions.

In this example, we’ll asynchronously read every character from a sizable text file to determine how long each character is.

Code Sample:

class Program
{ ke
static void Main()
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
int length = await task;
Console.WriteLine(" Total length: " + length);
Console.WriteLine(" After work 1");
Console.WriteLine(" After work 2");
}
Console.WriteLine(" File reading is completed");
return length;
}
}static async Task<int> ReadFile(string file)
{
int length = 0;
Console.WriteLine(" File reading is stating");
using (StreamReader reader = new StreamReader(file))
{
// Reads all characters from the current position to the end of the stream asynchronously
// and returns them as one string.
string s = await reader.ReadToEndAsync();
length = s.Length;
}
}

The code above calls the ReadFile function to read a text file’s contents and determine how many characters there altogether in the text file.

It will take a long time to read all the characters in our sampleText.txt file because there are too many of them.

 

Since we are utilizing async programming to read the entire contents of the file, the subsequent lines of code will be executed without waiting for the method’s return value. Because we are using the await keywords and we are going to use the return value for the line of code provided below, it must still wait for that line of code.

int length = await task;
Console.WriteLine(" Total length: " + length);

Then, more lines of code will be executed consecutively one after the other.

Console.WriteLine(" After work 1");
Console.WriteLine(" After work 2");

Result:

C# Async example

I/O-bound example: Download data from a web service

When a button is pressed, you might need to download some data from a web service, but you don’t want to obstruct the UI thread. It can be done in the following way:

private readonly HttpClient _httpClient = new HttpClient();
downloadButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI as the request
// from the web service is happening.
//
// The UI thread is now free to perform other work.
var stringData = await _httpClient.GetStringAsync(URL);
DoSomethingWithData(stringData);
};

Without becoming mired down in interactions with Task objects, the code above states the intention (asynchronous data download).

CPU-bound example: Perform a calculation for a game

Imagine you’re creating a mobile game where hitting a button will deal harm to a lot of the enemies you see. The damage calculation can be expensive, and running it on the UI thread would appear to pause the game while it is being done.

Starting a background thread that uses Task to complete the task is the best method to manage this.

Run and use await to check the outcome. As the job is being done, this enables the user interface to feel fluid.

private DamageResult CalculateDamageDone()
{
// Code omitted:
//
// Does an expensive calculation and returns
// the result of that calculation.
}
calculateButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI while CalculateDamageDone()
// performs its work. The UI thread is free to perform other work.
var damageResult = await Task.Run(() => CalculateDamageDone());
DisplayDamage(damageResult);
};

This code represents the button’s click event’s objective clearly, doesn’t call for manually managing a background thread, and does it in a non-blocking manner.

Key thing to keep in mind and understand:

  • I/O-bound and CPU-bound code can both employ async code, although in slightly different ways depending on the situation.
  • TaskT> and Task are constructs used in async programs to model work being done in the background.
  • The await keyword can be used in a method’s body since the async keyword converts it into an async method.
  • The await keyword suspends the calling method and returns control to the calling method until the task that is being awaited is finished.
  • Only async methods may utilize the await keyword.

How can you recognize CPU-bound and I/O-bound work

This guide’s first two examples demonstrated how to utilize async and await for CPU- and I/O-bound tasks, respectively. Knowing whether a task is I/O-bound or CPU-bound is essential since it can have a significant impact on your code’s performance and possibly result in the misuse of some constructs.

Before writing any code, you should consider the following two questions:

  • Is something going to be “waiting” for in your code, like data from a database?

Your job is I/O-bound if you replied “yes.”

  • Will your code need to run a pricey calculation?

Your task is CPU-bound if you indicated “yes” in your response.

If your work is task-bound by I/O, utilize async and await instead of Task. Run. Use of the Task Parallel Library is not advised.

If your workload is CPU-bound and responsiveness is important to you, utilize async and await, but use Task to spawn the work off into a different thread.

Run. Consider using the Task Parallel Library as well, if concurrency and parallelism are acceptable for the work.

Additionally, you should constantly monitor how your code is being executed. For instance, you might discover that the cost of your CPU-bound task is insufficiently high relative to the multithreading overhead associated with context shifts. Every decision has a trade-off, and you should make the best trade-off possible given your circumstances.

Important advices and information

  • Await must be a body keyword in async methods else they will never yield!

It’s crucial to remember this. The C# compiler generates a warning if await is not used in the body of an async method, but the code still compiles and executes as if it were a regular method. This is highly wasteful because the state machine the C# compiler created for the async method does nothing.

  • Every name you create for an async method should end with “Async.”

In.NET, this convention is used to more clearly distinguish between synchronous and asynchronous methods. It’s not always necessary to use methods that aren’t explicitly used by your code, such event handlers or web controller methods. Being specific in their nomenclature isn’t as crucial because they aren’t invoked directly by your code.

  • Only event handlers should utilize async void.

Because asynchronous event handlers cannot use Task and TaskT> because events lack return types, async void is the only way to enable them to function. Any other application of async void departs from the TAP paradigm and poses a challenge, such as:

  • An async void method cannot catch an exception that is thrown outside of it.
  • Testing async void methods is challenging.
  • If the caller does not anticipate them to be async, async void methods may have undesirable side effects.

 

  • When utilizing async lambdas in LINQ expressions, proceed with caution.

Deferred execution is used by lambda expressions in LINQ, which means that code execution could occur when you least expect it to. If not written properly, the addition of blocking jobs to this can quickly lead to a deadlock. Furthermore, the execution of the code may be harder to predict when asynchronous code is nested in this way. Although async and LINQ are strong together, they should be utilized with the utmost caution and clarity.

  • Anytime ValueTask is an option, use it.

Certain pathways may have performance bottlenecks as a result of async operations returning a Task object. Utilizing a task entails allocating an object because task is a reference type. The extra allocations can add up over time in performance-critical code sections if a method with the async modifier completes synchronously or returns a cached result. If those allocations take place in close loops, it can become expensive.

  • Think about use ConfigureAwait (false)

When should I utilize the Task.ConfigureAwait(Boolean) function is a frequently asked question. A Task object can configure its awaiter using this method. This is a crucial factor, and setting it improperly could have an impact on performance or possibly lead to deadlocks.

  • Make your code less stateful.

Don’t rely on the operation of specific methods or the state of global objects. Rather, just rely on the results of procedures. Why?

  • Code will be simpler to rationalize.
  • Testing code will be simpler.
  • It is much easier to mix synchronous and async code.
  • Usually, race-related situations can be completely avoided.
  • Coordination of async programming is made simple by relying on return values.
  • Dependency injection works pretty well with it.

expressions, or anonymous methods. It is treated as an identifier in all other situations.

Return Types

The subsequent return types are available for async methods:

  • Task
  • Task<TResult>
  • Since callers cannot await those methods and must design an alternative mechanism to indicate successful completion or error conditions, methods are generally avoided for programs other than event handlers.
  • Every type that has a reachable GetAwaiter function as of C# 7.0. The Program. Tasks. One example of this is the ValueTaskTResult> type. By including the NuGet package System, it is accessible. Threading.Tasks.Extensions.

The async method cannot declare any in, ref, or out parameters and cannot return a result that is a reference, but it can call methods that do.

If an operand of type TResult is specified in the method’s return statement, you must provide Task as the return type. If no useful value is returned when the method is finished, use Task. In other words, a method call returns a Task, but any await expression that was awaiting the Task evaluates to void once the Task has been finished.

The void return type is typically used to create event handlers, which need it. A void-returning async method’s caller is unable to anticipate it or catch any exceptions that it may throw.

Code Sample:

public static async Task DisplayCurrentInfoAsync()
{
await WaitAndApologizeAsync();
Console.WriteLine($"Today is {DateTime.Now:D}");
Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}");
Console.WriteLine("The current temperature is 76 degrees.");
}
static async Task WaitAndApologizeAsync()
{
await Task.Delay(2000);
Console.WriteLine("Sorry for the delay...\n");
}

Result:

Return async c#

Task<TResult> return type

For an async method with a return statement and TResult as the operand, the return type is TaskTResult>.

The return statement in the GetLeisureHoursAsync function in the example below returns an integer. Taskint> must be specified as the return type in the method declaration. The async function FromResult is a stand-in for an operation that returns a DayOfWeek.

public static async Task ShowTodaysInfoAsync()
{
string message =
$"Today is {DateTime.Today:D}\n" +
"Today's hours of leisure: " +
$"{await GetLeisureHoursAsync()}";
Console.WriteLine(message);
}
static async Task<int> GetLeisureHoursAsync()
{
DayOfWeek today = await Task.FromResult(DateTime.Now.DayOfWeek);
int leisureHours =
today is DayOfWeek.Saturday || today is DayOfWeek.Sunday
? 16 : 5;
return leisureHours;
}

Result:

tresult async

Void return type

Asynchronous event handlers, which need a void return type, employ the void return type. An async method that returns void cannot be anticipated, thus you should return a Task in place of it for methods other than event handlers that don’t return a value. Any caller of such a method must proceed all the way through without stopping to wait for the async method it called to finish. Any values or errors that the async method produces must not affect the caller.

Exceptions thrown by an async function that returns void cannot be caught by the method’s caller. Your program is likely to crash as a result of such unhandled exceptions. The exception is kept in the returned task if a method that returns a Task or TaskTResult> throws one. When the job is awaited, the exception is once again thrown. Ensure that calls to any async method that potentially throw an exception have an awaited return type of Task or TaskTResult>.

Code Sample:

public class NaiveButton
{
public event EventHandler? Clicked;
public void Click()
{
Console.WriteLine("Somebody has clicked a button. Let's raise the event...");
Clicked?.Invoke(this, EventArgs.Empty);
Console.WriteLine("All listeners are notified.");
}
}
public class AsyncVoidExample
{
static readonly TaskCompletionSource<bool> s_tcs = new TaskCompletionSource<bool>();
public static async Task MultipleEventHandlersAsync()
{
Task<bool> secondHandlerFinished = s_tcs.Task;
var button = new NaiveButton();
button.Clicked += OnButtonClicked1;
button.Clicked += OnButtonClicked2Async;
button.Clicked += OnButtonClicked3;
Console.WriteLine("Before button.Click() is called...");
button.Click();
Console.WriteLine("After button.Click() is called...");
await secondHandlerFinished;
}
private static void OnButtonClicked1(object? sender, EventArgs e)
{
Console.WriteLine(" Handler 1 is starting...");
Task.Delay(100).Wait();
Console.WriteLine(" Handler 1 is done.");
}
private static async void OnButtonClicked2Async(object? sender, EventArgs e)
{
Console.WriteLine(" Handler 2 is starting...");
Task.Delay(100).Wait();
Console.WriteLine(" Handler 2 is about to go async...");
await Task.Delay(500);
Console.WriteLine(" Handler 2 is done.");
s_tcs.SetResult(true);
}
private static void OnButtonClicked3(object? sender, EventArgs e)
{
Console.WriteLine(" Handler 3 is starting...");
Task.Delay(100).Wait();
Console.WriteLine(" Handler 3 is done.");
}
}

Result:

Void return type

Generalized async return types and ValueTask<TResult>

As a simple implementation of a task-returning value,.NET offers the System.Threading.Tasks.ValueTaskTResult> structure. You must include the System.Threading.Tasks.Extensions NuGet package in your project in order to use the System.Threading.Tasks.ValueTaskTResult> type. The value of two dice rolls is obtained using the ValueTaskTResult> structure in the example that follows.

class Program
{
static readonly Random s_rnd = new Random();
static async Task Main() =>
Console.WriteLine($"You rolled {await GetDiceRollAsync()}");
static async ValueTask<int> GetDiceRollAsync()
{
Console.WriteLine("Shaking dice...");
int roll1 = await RollAsync();
int roll2 = await RollAsync();
return roll1 + roll2;
}
static async ValueTask<int> RollAsync()
{
await Task.Delay(500);
int diceRoll = s_rnd.Next(1, 7);
return diceRoll;
}
}

Result:

Async return types

IoT Testing – Today’s and Tomorrow’s Technologies and Strategies

IoT Testing – Today’s and Tomorrow’s Technologies and Strategies

IoT Testing

Internet Of Things (IoT) Testing: Tools And Testing Approach

The Internet of Things has emerged as a top-trending technology, with greater supply and demand than ever for IoT solutions. But it is only the beginning.

The most cautious projections predict that there will be 25,44 billion linked IoT devices by 2030, if there were over 7,74 billion in 2019. If we can solve the interoperability and security problems with IoT technologies, that number will rise even further.

The need of maintaining the effectiveness and security of the system increases as more devices connect to the Internet of Things. Traditional methods for providing quality assurance services, however, are insufficient today. Early testing is necessary for many devices, especially those that are undergoing continuous integration.

What is Internet of Things (IoT)?

Three essential elements make up the Internet of Things: devices, communications, and computers. Devices are items or actual physical things that are linked to the Internet. The second part of the system is communication, which can be done using Wi-Fi, satellites, or cellular connections. Communication is crucial to keeping the system running.

The system can function effectively thanks to the third component, computation, which is carried out in a central location on the server. For intelligent decision-making, an IoT application helps combine all three components.

The implementation of common IoT solutions globally is hampered by the heterogeneity of underlying devices and communication technologies as well as the need for interoperability at various levels, from communication and seamless integration of devices to the interaction of data generated by IoT resources.

Because the IoT is a real-time network, performance and security issues in any one area can have an adverse effect on the operation of the entire network. A cyberattack on one node can impact neighboring nodes. As a result, you must find every weak area before the product is sold to customers.

IoT testing is a set of QA tests for validating functionality, performance, and security for any devices, independent of their size, location, or other characteristics.

There are several challenges with the testing process because the IoT is a fragmented system. By assembling sizable test teams to check every component’s dependability across various platforms and devices, these can be eliminated.

IoT Examples

Here are a few instances of IoT implementation in daily life:

1. Smart watch

 

IoT Example

Apple watches and Fitbit bands are two examples of wearable technology that sync effortlessly with mobile devices.

These aid in gathering important data, including that related to health, heart rate monitoring, sleeping patterns, etc. These aid in showing information and notifications from mobile devices.

2. Infrastructure and development:

It is simpler to obtain real-time outdoor lighting data with the aid of a program like CitySense, and the street lights are turned on or off as a result. In a complex metropolitan plan, there are also numerous applications to manage traffic signals and parking availability.

3. Healthcare

There are many programs available to track patients’ health issues.

The services regulate the medication dosage throughout the day based on benchmarked data. There are programs like UroSense that can track the patient’s body’s fluid levels and, if necessary, start a fluid transfer. The data can be remotely distributed to many stakeholders at the same time.

The technology behind IoT

The few most popular IoT technologies are as follows:

  • EPC [Electronic Product Code] and RFID [Radio Frequency Code] tags
  • To allow for two-way communication between the electronic gadgets, NFC [Near Field Communication] is utilised. Essentially, this is for cellphones and is primarily used for contactless payments.
  • When short-range communications are sufficient to solve the issue, Bluetooth is used. The majority of wearable technology uses this.
  • A low power RF communication technology is Z-Wave. This mostly serves the purposes of home automation, lamp control, etc.
  • IoT devices are most frequently connected via WiFi. This facilitates the smooth transport of files, data, and messages over a LAN.

What kinds of IoT testing are there?

Although testing IoT solutions has some unique quirks, in theory it is similar to evaluating other software products. There are two main categories of test types, each of which has its own subcategories.

Functional Testing

It entails examining the operation of numerous functional characteristics, as you might infer from the name. This group consists of, for instance:

  • Unit tests Each module or piece of an application is tested. Usually, the IoT development team handles this work.
  • Integrity test. It is crucial to understand how the modules function together once they have all been merged.
  • End-to-end testing. This method entails testing the complete piece of software.
  • Smoketesting: This kind of testing determines whether the software is sufficiently stable.
  • Regression analysis. Program changes result from each new module that is added. If the IoT device’s firmware needs to be updated, this could result in system modifications as well. After each update, it is critical to verify that all components are still operating properly.
  • Interface evaluation. The GUI is tested to ensure it complies with all standards and specifications.

Non-functional Testing

It emphasizes elements like effectiveness, dependability, and security. We can define the following types under this heading:

  • Performance testing. The goal of this approach is to find software performance issues.
  • Security testing. This kind of testing is extremely thorough because data security is essential to the majority of IoT systems.
  • Load testing. By doing so, you may figure out how much load the software can handle without suffering performance degradation.
  • Stress testing. When there are limited resources, these tests assist you in determining whether the system is operating as planned. Compatibility testing. It will assist you in determining whether the program can operate without errors or other issues across a variety of platforms and environments. When the software is 100 percent stable, these tests are appropriate.

Up to 40 different testing types are available overall. Let’s look more closely at the most popular solutions for the Internet of Things.

Compatibility testing

Compatibility tests should be done first since IoT systems are created using a variety of hardware and software configurations. This is because this is the most important stage of IoT testing. To ensure maximum compatibility, this process often entails testing multiple hardware, browsers, operating systems, and communication methods.

It establishes compatibility between a target product that implements a standard specification and other products that implement the specification exactly. Each piece of software must be able to recognize input from other programs, manage the workload necessary for it to play its part in the architecture, and produce outputs that are useful and accessible.

Tip: Verify that the data sent is valid and that the response time was within a certain window of time.

Performance testing

Starting with the performance-related implementation validation, the second stage of IoT software testing is carried out. The performance testing process often addresses a number of important elements, such as:

  • Performance when dealing with a lot of data.
  • Testing a system with multiple devices at once.
  • Device communication checks.
  • Usability of the system, including RAM load, battery life, and power utilization.
  • Putting the gadget through a variety of network and environmental tests.

It enables you to evaluate the performance of IoT applications in environments with lots of data. The application can be tested in difficult situations utilizing custom scripts and cloud platforms to mimic large loads.

Tip: As a general rule, performance testing for the Internet of Things (IoT) should be done at the network and gateway level (using protocols like MQTT, HTTP, and CoAP), system level (processing, analytics, and databases), and application level.

Connection testing

Even in the event that customers do not have access to all of the data, the third testing phase guarantees continuous connectivity. The connectivity between the hub and the devices affects how stable the IoT system is. After all, if the connection is lost for at least one second, it may result in inaccurate data and unstable systems. One of the two key components of connectivity testing, along with data recovery, is flawless connectivity.

Tip: Don’t forget to register with the network any devices used in the IoT test. Make sure the mistake continues by sending ping packets on a regular basis. To reestablish connectivity, the device must save the data to the database and sync it with the hub (device shadow in AWS).

Usability testing

IoT software interfaces must be user-friendly and instructive because users of IoT devices receive data in real-time. Usability testing makes ensuring that the software is simple, intuitive, and accurately reflects all the graphical aspects for the user.

Tip: Make that the IoT application has all of its features, complies with the requirements, and is tested for user experience (UX).

Security testing

IoT security testing approaches are crucial for creating a strong IoT testing strategy since IoT software needs a lot of data to operate properly. There are three testing levels in it.

  • Testing the network It defends against potential network layer assaults on the IoT application.
  • System evaluation. It will make sure that user data is secure and effectively guarded against hacks and leaks.
  • IoT device testing. This type of test guarantees that IoT application-related devices are shielded from issues with APIs, authentication, updates, configuration settings, etc.

Tip: On jailbroken devices, ensure sure you can remotely delete data or look for signs of unauthorized access to the device.

Beta testing

User testing of this nature Realistic IoT test scenarios must be modeled by testers. The likelihood of a successful release is increased and they are able to stop users from experiencing issues with the IoT application’s final version. As bugs and usability problems are found during the beta stage, it also aids business owners in lowering bug fixing expenses.

You can test IoT applications at every level of development by using IoT testing.

IoT Testing framework: What is it all about?

User testing of this nature Realistic IoT test scenarios must be modeled by testers. The likelihood of a successful release is increased and they are able to stop users from experiencing issues with the IoT application’s final version. As bugs and usability problems are found during the beta stage, it also aids business owners in lowering bug fixing expenses.

You can test IoT applications at every level of development by using IoT testing.

  • Application layer. At this stage, testing is done for APIs, functionalities, compatibilities, usability and user experiences, and localization.
  • Service level. Compatibility testing, functional testing, and API testing are carried out at this level.
  • Gateway and network layer. It has to do with verifying network connectivity and compatibility.
  • Sensory level. The tester will do functional and security testing at this stage.
IoT Testing Framework

What are some typical IoT testing obstacles, and how can they be overcome?

The finest Internet of things software testing solutions should anticipate any potential difficulties that could make the testing process more difficult for developers and QA professionals. Let’s examine the most significant ones first:

Lack of uniformity

To start, consider how the IoT environment needs to be standardized at several levels, including connectivity, communication protocols, platforms, and business models. But this doesn’t happen very often. Each link in an IoT network often includes its own hardware and software. This implies that test cases for each type of hardware and software must be included in IoT testing services.

Tip: It’s not always a good idea to run every script at once. The best possible integration combinations are tested using test cases that are available on the market.

Security vulnerabilities

IoT devices must consistently pass security testing since they can be subject to cybersecurity attacks if they produce a lot of data. Security flaws can then be found and fixed in this manner. Use of technologies that verify password prompts and behavior on an IoT device upon initial user access, for instance, is crucial.

Tip: Try to find flaws in firmware and device architectures from the standpoint of an attacker. See our IoT penetration testing guide for insights and tips.

Diverse communication protocols

Devices use a variety of real-time communication protocols in an IoT setting, including XMPP, AMPQ, MQTT, and CoAP. These protocols aid in establishing connections both between devices and with the server.
Additionally, several IoT system components have access to additional communication protocols. Latent failures will continue to pose functional or security issues up until the point at which we test these components over communication channels.
When loading requests go over a certain threshold, sensors built into the device may run out of memory. As a result, they employ an IoT gateway to distribute the load demands among the components rather than sending these requests directly to the sensors. IoT testing increases the lifespan of components and confirms the load distribution between them

Tip: To make sure they operate effectively, dependably, and securely, every IoT device needs to be tested using communication protocols..

The main advantages of IoT testing for your company
Check out the following main benefits of testing for IoT solution users in the corporate world:

  • New commercial opportunities Software testing for the Internet of Things will hasten efforts with lower risk and promote innovation.
  • Time-to-market is accelerated through IoT testing, which makes use of early automation.
  • Better interoperability is achieved by IoT QA testing, which guarantees that end users receive a high-quality user experience across all channels.
  • Higher ROI. IoT testing offers a thorough method for confirming the functional and non-functional needs of IoT systems. Delivering safer solutions will make you more appealing to your clients, and vice versa.

Examples and suggestions for testing IoT applications

IoT application testing is primarily distinguished from testing other types of software by the fact that the latter’s connection to external devices is fundamental. In this case, the testing team needs to be well knowledgeable about these devices and their functions.
The testing procedure is facilitated when programmers have physical access to the necessary hardware. To access the gadget, though, is frequently not possible under certain circumstances. As a result, in order to replicate a particular setting and interaction, testers must employ specialist software.

What equipment is used to evaluate IoT applications?

The instruments listed below can be used to run a wide range of IoT tests:

  • Instrument/protocol simulators. They enable you to imitate standard-compliant devices and then modify them to display the precise states you want, which is why testers utilize them when there are significant discrepancies between device endpoints and their interfaces.
  • Tools for API testing: Web services and REST APIs are being used more frequently to build solutions. Their connectivity, responsiveness, and performance are checked using tools like Postman, Progress®, and SoapUI.
  • Tools for playback and recording. To automate test execution, devices or applications, systems, and user data/actions can be recorded and replayed on simulators and applications.
  • Data loggers from many gadgets. The recorded data automatically plays on additional device endpoints, assisting in the testing of an application’s suitability for use across a range of hardware and communication layers.
  • Tools for mobile testing. These offer fully automated mobile testing that validates the app’s functionality and mimics the end-user experience.
  • Tools for virtualization. Real-time IoT app behavior monitoring is challenging and time-consuming. Additionally, virtualization solutions enable the rapid and cost-effective execution of compatibility testing without the need to purchase expensive hardware, databases, platform services, etc.
  • Tools for automatic deployment. They are used to configure and install specially created services and applications as well as swiftly deploy managed services, construct virtual machines programmatically on-premises or in the cloud. In continuous build, integration, and deployment environments, staging capabilities are provided by tools like Katello, Foreman, and Ansible Tower®.
  • Tools for testing security. These are subdivided into runtime threat production tools, static code analysis tools, and threat modeling tools. Threats can be identified, prioritized, and remedied using tools like OWASP ZAP, VGC, and Microsoft® Threat Modeling Tool. Two open-source security tools that can assist with vulnerability detection are Acunetix® and Netsparker®.
  • Supplementary tools You may test IoT systems using the following tools and equipment:
    JTAG Dongle and digital storage oscilloscope for IoT testing equipment and tracking its parameters. Wireshark® and Tcpdump for network traffic monitoring.

Testing timeframes

Traditional testing techniques take a lot of time and are typically used after product creation. This is unacceptable in the fast-paced, fiercely competitive climate of today.
The easiest method to identify and address any possible issues as soon as they arise is to test frequently and early. For IoT platforms, where continuous integration is the core of the technology, this is particularly crucial. It is intended to plan product testing phases in a manner that corresponds to active development.

Process plan for IoT Testing

  • Assembling a team to test IoT applications;
  • Creating a strategy and test plan for the IoT application and its individual modules;
  • Choosing a test type based on the unique characteristics of each IoT system component;
  • Selecting a suitable selection of testing tools;
  • Establishing an IoT testing facility;
  • Creating, running, and maintaining IoT scenarios and test cases;
  • Analysis and eradication of potential issues during application testing;
  • Creation of test-related reports and documentation.
Iot Tetsing Process Plan

IoT system test protocol

The normal operation of the application may be hampered by the technical properties of IoT devices and issues with the devices’ firmware. When we come across such problems while testing, we inform clients of our findings and suggest adjustments.
The client sends us instructions for upgrading the software after making a change to his device. To guarantee that the entire system continues to operate as intended following updates, these modifications necessitate redoing the regression testing stage.
The following steps are involved in standard IoT testing:

Component inspection

We examine the following parts:

  • Connectivity to a network.
  • Software programs.
  • Internal sensors.
  • Hardware tools.
  • Security apparatus.
  • Cloud or server infrastructure

Check for functionality

Only when necessary should the IoT system react and perform. Each connected gadget also needs to communicate effectively. In doing so, we test:

  • Errors and exceptions.
  • Transferring data across devices.
  • System reaction.
  • Results of a calculation.

Check the conditions

Testing was done in the most extreme circumstances. The responses of the IoT system have also been saved by testers in the following formats:

  • Automated parameters.
  • Manual circumstances.

Performance review

We base our calculations of an IoT system’s performance on the following elements:

  • Failure of the system happens.
  • Frequency of data transmission.
  • Device functionality.

In the end, we offer in-depth reports on found vulnerabilities, tools and techniques for exploiting system faults, and suggestions for removing found hazards.

Best practices for testing IoT software

We’ll now provide you with some insightful advice on how to test mobile applications to steer clear of typical performance issues.

Automate established testing techniques
It makes sense to automate some repetitive activities due to the accelerated pace of R&D and the requirement to enter the market first. Automation, however, necessitates not just the appropriate tools and technologies, but also highly skilled specialists. The ideal course of action is to automate only established processes, especially those with a high return on investment.

Utilize the potential of cloud services.
You may test how IoT apps respond to heavy data loads by simulating high loads on them using the power of cloud computing. Additionally, the technique aids in determining how much data the IoT application sends to the hub, particularly when the IoT devices are operating at low power. Since it serves as a great gauge of the usability of IoT apps, this point needs extra consideration from the QA side.

Ensure safety and usability
If the device includes a payment option, it must to be quick and secure. The user should lock the smart device through their mobile devices or IVR in the case of a loss of a wearable gadget.

Conclusion

Testing IoT systems is a difficult undertaking, thus expertise is important. KoderShop, a provider of IoT software, possesses this knowledge and can test usability, security, performance, connectivity, and compatibility in:
Mobile software (supported on the platforms of Amazon, iOS, Android, and Windows); device firmware; equipment and mobile device integration (BLE, Wi-Fi sync);

API (allows mobile applications or hardware to sync and store data with the cloud);

Data security: Token-based, key-based, and OAuth authentication and authorisation protocols; role-based access; manual XSS/SQL injection; cache storage security (keyboard, browser, app).

String Methods Python and Their Options – Can List Of Symbols Be Practical?

String Methods Python and Their Options – Can List Of Symbols Be Practical?

String Methods Python and How to Manipulate a String

Python string method
Python string method

Definition of String in Python

A string is a data type that is used to describe textual content in different programming languages.

In Python, a string is a sequence of Unicode characters, but there is no single character data type, so it’s also a string, which has a length of 1. Unicode was introduced to include every character. Also it brings uniformity in encoding.

To create strings you need to enclose characters inside a single quote, double-quotes or triple-quotes (in cases spanning strings over multiple lines). Also strings don’t have any limits in length or using upper-case letters. Actually, <str> represents the Python string class. In accordance, the str() function can convert a value into a string data type.

str_single_quotes = 'Welcome to KoderShop' 
print(str_single_quotes)
#output:
#Welcome to KoderShop

str_double_quotes = "Welcome to KoderShop" 
print(str_double_quotes)
#output:
#Welcome to KoderShop

str_triple_quotes = '''Welcome
to
KoderShop'''
print(str_triple_quotes)
#output:
#Welcome
#to
#KoderShop

String Manipulation in Python

String manipulation means that you can change something in the string. To do this you need built-in string Python methods.

You already know how to create a string so here are examples how to access string characters and how to know the length of it.

 

Example of accessing:

example = "Hello KoderShop"
character = example[6]
print(character)
#output
#K

Example of len():

example = "Hello KoderShop"
print(len(example))
#output
#15

There are 47 built-in string methods in Python.

Upper() and lower() Methods

Starting from the base there are a few functions that can make letters in the string uppercase and lowercase. They are upper() function and lower() function and also they are capitalize() method that makes only first letter uppercase.

 

Examples of these string operations in Python:

example = "python is a masterpiece!"
print(example.capitalize())
#output:
#Python is a masterpiece!

example = "Python is a masterpiece!"
print(example.upper())
#output:
#PYTHON IS A MASTERPIECE!

example = "PYTHON IS MASTERPIECE..."
print(example.lower())
#output:
#python is masterpiece...

Moreover if you want to capitalize every word in your sentence, there comes the title() function, obviously used for titles in your articles.

example = "String methods in Python"
print(example.title())
#output:
#String Methods In Python

Swapcase() Method

If you want to switch lowercase letters to uppercase and vice versa in a string, you can use swapcase() function.

example= "kODERsHOP"
print(example.swapcase())
#output:
#KoderShop

Isupper() and islower() Python String Operations

To check the previous functions we can use these methods. Isupper() is used to check letters for their uppercase. And the same thing is with islower(). They both return boolean types.

example = "PYTHON IS MASTERPIECE..."
print(example, "is uppercase:", str(example.isupper()))
#output:
#'PYTHON IS MASTERPIECE...' is uppercase: True

example = "PYTHON IS
MASTERPIECE..."
print(example, "is lowercase:", str(example.islower()))
#output:
#'PYTHON IS MASTERPIECE...' is lowercase: False

Isalnum(), isalpha(), isdecimal() String Functions Python

Isalnum() Method

This function we can use for checking if the string has numeric and alphabetical symbols. It can be useful, for example, for passwords.

example =
"ABCDEFJHIJKLMOPQRSTUVWXYZ"
print(example, "contains symbols from alphabet:", str(example.isalnum()))
#output
#ABCDEFJHIJKLMOPQRSTUVWXYZ is an alphabetical order: True

example = "123@34"
print(example, "contains only numbers:", str(example.isalnum()))
#output
#123@34 contains only numbers: False

Isalpha() Method

This function you can use for checking whether our string has only alphabetical symbols.

example = "ABCD_EFJHIJKLMOPQRSTUVWXYZ"
print(example, "contains symbols from alphabet:", str(example.isalnum()))
#output
#ABCD_EFJHIJKLMOPQRSTUVWXYZ is an alphabetical order: False

Isdecimal() Method

Obviously, the name of the method says its operation. It checks whether our string has only tenfold numbers:

example = '_54'
print(example.isdecimal())

example = '54'
print(example.isdecimal())
#output
#False
#True

Python String Functions center(), rjust(), ljust()

Center() Method

Actually, this function pads your string variable using default (“Space”) or specified characters. It tries to center your string text into the given length.

example = "Hello, world!"
new_example = example.center(30)
print('|' + new_example + '|')
#output:
#| Hello, world! 

As we can see, our “Hello world!” is centered between two vertical bars. Here is one more example to see how it works:

example = "Hello, world!"
new_example = example.center(30, '=')
print('|' + new_example + '|')
#output:
#|========Hello, world!=========|

We have used the equals sign as a filling symbol in this example.

Rjust() and Ljust() String Python Methods

It works the same as center() string function python but pads your string on the right side using default symbols(‘Space’) or symbols that are written in attribute.

 

Ljust() obviously is the same as rjust() function but pads on the left side.

example = "Hello, world!"
new_example = example.rjust(30)
print('|' + new_example + '|')
#output:
#| Hello, world!|

example = "Hello, world!"
new_example = example.ljust(30)
print('|' + new_example + '|')
#output:
#|Hello, world! 

Count() Method

This function is one of python string built in functions that can return how many times the given text has occurred. The name of the function says what it means.

example = "hello, my friends, hello..." 
print(example.count("hello"))
#output:
#2

but:

example = "Hello, my friends, hello..." 
print(example.count("Hello"))
#output:
#1

So, it is very strict about the case of given letters. 

Another thing about count() function in Python is that you can give the indexes between which it should count:

example = "hello, my friends, hello..." 
print(example.count("hello", 0, 5))
#output:
#1

0 and 5 are indexes of letters used for our interval.

example = "hello, my friends, hello..."
print(example.count("hello", 0, 27))
#output:
#2

Encode() Method

Factually, encoding is converting text that is written in one system language into another. Being a simple person you can use character UTF-8 encoding for your descriptions or texts. It is good in encoding a single character to any you want to use. This Unicode easily helps you in everything. That’s why creating HTML websites or PC systems need to have it written inside as it removes tracking for right conversion.

But anyway there can be situations where you need not UTF-8 but another. That’s where one of python strings methods, the encode() method comes in.

example = "python" 
print(example.encode('cp037'))
#output:
#b'\x97\xa8\xa3\x88\x96\x95'

Python String Function Endswith()

Endswith() method is used for checking if the string variable has the symbols we have given. Again the name of the function can say all what it means.

 

example = "hello, my friends, hello..." 
example = "helloworld"
print("Does our first string have this ending?", str(example.endswith("world")))

example = "helloworld."
print("Does our second string have this ending?", str(example.endswith("world")))
#output:
#Does our first string have this ending? True
#Does our second string have this ending? False

In output “this ending” means “world” so it helps us to see how the endswith() function works. It is strict to written symbols, so if there is at least one comma or dot, it counts.

Find() and index() String Functions in Python

Find() Method

One of the base functions used for string is find(). It is easy to use and is very powerful. Obviously you can use it for finding words in written strings.

example = 'Hello, KoderShop'
print(example.find('KoderShop'))
#output
#7

In this python string method example the start of ‘KoderShop’ is on the 7th symbol. But if the find() function can`t find anything it returns ‘-1’:

example = 'Hello, KoderShop'
index = example.find('hello')
print("'hello' word is found at:", index)

index = example.find('kodershop')
print("'kodershop' found at index:", index)

Another good example of find() usage in string is:

example = 'Hello, KoderShop'
word = 'Wikipedia'

if example.find(word) != -1:
print( word, "contains in string")
else:
print( word, "doesn't contain in string")
#output
#Wikipedia doesn't contain in string

Index() Method

index() method itself helps you to find the first index where the given string is located. Here is an example of this string command python:

example = 'python string functions examples'
print(example.index('but'))
#output:
#ValueError: substring not found

And obviously, here we can see the difference between find() and index() string functions in Python. When find() returns ‘-1’, the index() returns an exception. It is the only difference. In another it is the same as find().

Python String format Method

If you want to have a possibility to add and edit words anywhere in the string, you can use the format() string method.

example = "This article is written by
{}"
print(example.format("KoderShop"))
#output:
#This article is written by KoderShop

Additionally for using more than one pair of brackets it would be better to add placeholder values inside the brackets.

example = "This article is written by {company}. It is about {topic}."
print(example.format(company = "KoderShop", topic = "string methods"))
#output:
#This article is written by KoderShop. It is about string methods.

Format_map() Method

With this method you can have a dictionary with words and their keys and use these keys to have access to the words in the string. It has the same python string operation as the built-in dictionaries in Python 3.

dictionary = {'company':'KoderShop', 'topic':'string methods'}
print("This article is written by {company}. It is about {topic}.".format_map(dictionary))
#output:
#This article is written by KoderShop. It is about string methods.

Python String Methods split() and rsplit()

Split() Method

It allows you to split the words using space, semicolon or other symbols. For example, having one string you can have a list of words from it.

example = '2022 – the best year'.split() 
print(example)
#output:
#['2022', '–', 'the', 'best', 'year']

example = '2022 – the best year'.split('–') 
print(example)
#output:
#['2022 ', ' the best year']

You can see how we use ‘t’ as separator below:

example = '2022 - the best year'.split('t') 
print(example)
#output:
#['2022 - ', 'he bes', ' year']

Split() function and its own attributes split(separator, maxsplit) :

maxsplit()

maxsplit() is the attribute that makes the maximum number of splits that must be done. It is a very useful one.

example = '2022 - the best year'.split(' ', maxsplit=1) 
print(example)
#output:
#['2022', '- the best year']

Here we used the space as a separate symbol and made the maximum amount of splits 1.

separator()

separator() obviously is our separate symbol that we used before. It can be as ‘ ‘, as ‘t’ and even as  ‘#’ !

example = '2022#-#the#best#year'.split('#') 
print(example)
#output:
#['2022', '-', 'the', 'best', 'year']

Rsplit() Method

It allows you to split the words the same as the split() method that was mentioned before, but it does it starting from the right side. The clear example of it is using the maxsplit().

For instance, it can be used when we have a maxsplit() attribute that equals ‘1’ and we want to split only one word at the end.

example = '2+2+2+3'.rsplit('+', maxsplit=1) 
print(example)
#output:
#['2+2+2', '3']