sec01 - String Operations and Type Casting

String Operations and Type Casting

String concatenation

You can concatenate strings using the + operator. Try executing the following code.

s = 'Hello, ' + 'I am Nico.'
print(s)

When you run the above code, the strings Hello, and I am Nico. will be concatenated and output as shown in the figure below.

When concatenating strings, if you need to insert a delimiter, such as a space, between the characters to be concatenated, you must prepare it in advance. If you know that strings will be concatenated, you can insert a comma and space in advance, as shown in the code above with ‘Hello, ’.

Another way to write this is as follows.

greeting = 'Hello'
my_name = 'I am Nico.'
s = greeting + ', ' + my_name
print(s)

In the first two lines of the above code, ‘Hello’ and ‘I am Nico.’ are assigned to variables, but there are no spaces or commas before or after each string. When this code is executed and the characters are concatenated, the result will be “HelloI am Nico.”. To avoid this result, you need to write code that inserts commas and spaces between each string.

Next, let's look at the result of concatenating characters that contain numbers. Try executing the following code.

s = '123' + '456'
print(s)

Since the characters ‘123’ and ‘456’ are concatenated, a string of numbers will be output as shown in the figure below.

In the case of “numbers as characters,” addition is not performed as it is with numbers. String-type data manages the characters (numbers as characters) in order from left to right, and does not manage them as numbers (int/float). Therefore, regardless of whether the contents of the string are alphabetic characters or numbers, the + operator used with string types behaves as “concatenating characters.”

string and int/float

Next, let's try executing the code that connects string and int/float with the + operator.

s = '123' + 456
print(s)

Executing the above code results in the error shown in the figure below.

The error message is “TypeError: can only concatenate str (not "int") to str”. In other words, you cannot use the + operator to process the string '123' and the integer 456. (Of course, this error also occurs when combining strings and floats, not just strings and integers.)

Type casting to string

As in the previous example, when the types do not match, you need to convert one of them. If you want to concatenate them as strings, use the str() function to convert int or float values to strings.

The following code is an example of converting an int value to a string type and then concatenating it.

age = 10
s = 'I am ' + str(age) + ' years old.'
print(s)

The above code concatenates numbers with other strings to generate the string ‘I am 10 years old.’.

The first line assigns the integer to the variable ‘age’. The second line concatenates characters, but since integers cannot be concatenated as they are, the str() function is used to convert them to the string '10'. The str() function converts int/float type numbers to strings appropriately.

Type casting to int/float

Next, when converting strings to int/float, use the int()function to convert to integers and the float()function to convert to floating-point numbers.

The following example is a code example that takes two user inputs and adds the numbers together.

str_num1 = input('Enter first number: ')
str_num2 = input('Enter second number: ')
result = float(str_num1) + float(str_num2)
print('The result is:', result)

When you run this code in Visual Studio Code, a line that accepts user input will appear in the TERMINAL as shown in the figure below. (A rectangle indicating where to enter text will appear at the very end.) Place the cursor there (by clicking with the mouse, etc.), enter a number, and press the Enter key to confirm. (Repeat this two times.)

Enter two numbers and press Enter to display the sum of the two numbers you entered.

The explanation of the code: The first line, the input()function, is a function that accepts input from the user. Inside the parentheses, a message to the user is set. The data entered by the user is assigned to the ‘str_num1’ variable as a String type, even if a number is entered. The second line, input(), is the same, and a String type value is assigned.

In the third line, the input received from the user is converted to a float. To convert to a floating-point number, use float(). Once converted to a float, addition can be performed. (If not converted to a float, the string ‘123.4555.05’ will be concatenated.) The result of the float addition is assigned to the ‘result’ variable, and finally, the result is printed.

In this way, when you want to perform arithmetic operations on numbers or process data as numbers, convert them to int or float before processing.

Points to note when converting numbers as strings to int/float

This code will work without any problems as long as the user enters the correct numerical values. However, if the input cannot be converted to a numerical value, an error will occur. Additionally, there are restrictions such as using the int() function with strings representing floating-point numbers (e.g., ‘12.3’), which will result in an error. (Strings representing integers can be converted using the float() function.) For detailed specifications, please refer to the official documentation. If you encounter an error when running the code, please check the error message and try to identify and resolve the issue.

Incidentally, when writing programs that accept user input in actual work situations, it is necessary to take measures such as writing exception handling code to prevent the program from stopping due to input errors. (This avoids the program stopping due to errors by describing the processing method for incorrect input separately from the processing method for correct input.)

Exception handling will be explained in detail in a separate lecture.

Repeat string generation

To repeat a string, use the * operator.

Let's write the code as follows and try executing it.

s = 'Hello' * 5
print(s)

s = '=' * 30
print(s)

The output results will be as shown in the figure below.

Hello’ is repeated five times to produce ‘HelloHelloHelloHelloHello’, followed by ‘=’ repeated 30 times to produce ‘==============================’.

This technique may not have many applications, but it can be helpful when you want to print long lines, such as the second line.