Organize types in Python

This time, we will check the data type.

String type

How to express characters. "What's the weather like today?" In python, it is expressed by enclosing it in "" (double quote) "or"'(single quote) ". The escape character is "\ (backslash)"

python


msg1 = "How is the weather today?"
msg2 = 'How is the weather today?'
msg3 = "\"How is the weather today?"

In Java, it is expressed by enclosing it in "" (double quotes). If it was surrounded by "'(single quote)", it was a char type. In python, there seems to be no mechanism for expressing characters (char). By the way, the escape character is "\ (backslash)"

Java


String msg1 = "How is the weather today?";
String msg2 = "\"How is the weather today?";
char c = 'now';

Manipulating strings

Linking

If you want to concatenate strings in python, simply concatenate the strings with "+".

python


a = "at first"
b = "second"
c = a + c
print(c)  # =>First and second

There seems to be a way to use a list (I'll write it later).

print("".join(["at first", "second"]))  # => at firstsecond

Java


String a = "at first";
String b = "second";
String c = a + c;
//It's better to use StringBuilder.
// StringBuilder c = new StringBuilder(a).append(b);
System.out.println(c);  // =>First and second

Repeating letters

This is the first grammar I've seen in python. You can use "*" to represent a repeating string.

python


a = "One"
print(a * 5)  # =>One by one one by one

Java


String a = "One";
//Since there is no repetition in Java, use Stream or StringUtils of Commons lang.There is no choice but to use repeat
System.out.println(IntStream.rangeClosed(1, 5).mapToObj(i -> a).collect(Collectors.joining()));  // =>One by one one by one

Extraction of characters

A function to extract characters from any location from a character string.

python


a = "ABCDEFGHIJK";
print(a[2])  # => C

Java


String a = "ABCDEFGHIJK";
System.out.println(a.charAt(2));  // => C

Cut out characters

Cut a part from the whole string so that only the CDE in ABCDEFG is taken out. In python, you can cut out with the target character string [index of the start position of the character to be cut out: index of the end position of the character to be cut out -1]. If you want to cut out a certain character, use the target character string [: Index of the end position of the character to be cut out -1]. If you want to cut out after a certain character, use the target character string [Index of the start position of the character to be cut out:]. The fact that it can be cut out in this way means that the python string is also represented in the form of a list of characters.

python


a = "ABCDEFGHIJK";
print(a[2:5]) # => CDE
print(a[2:])  # => CDEFGHIJK
print(a[:5])  # => ABCDE
print(a[:-1]) # => ABCDEFGHIJ

Java


String a = "ABCDEFGHIJK";
System.out.println(a.substring(2, 5));  // => CDE
System.out.println(a.substring(2));     // => CDEFGHIJK
System.out.println(a.substring(0, 5));  // => ABCDE
//This way of python (a[:-1]) I didn't know how to apply.

Also, there seems to be a way to specify how many characters to cut out when cutting out. I was taught. I don't think it's used much, but it's worth remembering.

python


a = "ABCDEFGHIJK";
print(a[::3]) # => ADGJ
print(a[1::3]) # => BEHK

Java


String a = "ABCDEFGHIJK";
//I could only think of this in Java.
System.out.println(IntStream.range(0, a.length())
                   .filter(i -> i % 3 == 0)
                   .mapToObj(i -> String.valueOf(a.charAt(i)))
                   .collect(Collectors.joining()) );  // => ADGJ

Judgment of the presence or absence of characters

Use "in" to see if a string is included in the string. You can also use the find function to determine. By the way, find returns the index of the position where the character string specified in the argument first appears. If the string is not included, "-1" will be returned.

python


a = "ABCDEFGHIJK";
print("G" in a)         # => True
print(a.find("G") >= 0) # => True

Java


String a = "ABCDEFGHIJK";
System.out.println(a.contains("G"));      // => true
System.out.println(a.indexOf("G") >= 0);  // => true

String length

Check using the len () function. It will be returned as an integer type.

python


print(len("AIUEO")) # => 5

Java


System.out.println("AIUEO".length());  // => 5

Personally, I like the Java format because it matches the Japanese grammar as "How long is Aiueo?".

Numeric type

Integer type (int)

The integer type of python is expressed by inputting numerical values such as "1" and "2" as they are.

python


num1 = 1
num2 = 2

Java


int num1 = 1;
int num2 = 2;

Calculations between numerical values can be performed by four arithmetic operations (+,-, *, /), remainder calculation (%), and exponentiation calculation (**). Note that the value returned by division (/) is of floating point type. If you want to return an integer type by division, use //. Then, the decimal point is truncated.

python


4 + 2    # => 6
6 - 2    # => 4
4 * 2    # => 8
4 / 2    # => 2.0
4 // 2   # => 2
5 / 2    # => 2.5
5 // 2   # => 2
5 % 2    # => 1
4 ** 2   # => 16

By the way, in Java it is as follows. Also, Java has no easy way to do exponentiation.

Java


4 + 2          // => 6
6 - 2          // => 4
4 * 2          // => 8
4.0 / 2.0      // => 2.0
4 / 2          // => 2
5 / 2          // => 2
5.0 / 2.0      // => 2.5
5 % 2          // => 1
Math.pow(4, 2) // => 16.0

Float type

Use when dealing with decimal numbers. You can use the same operators as integer types.

Boolean

True or False. In python, just write "True" and "False". Negation is preceded by not. Please note that the first letter is uppercase. Negative not is all lowercase. In addition, None, numerical value 0, and empty ("", [], ()) are judged as False, and others are judged as True. ~~ Also, be careful as the number 1 is judged to be True. ~~ The bool type is a subclass of the int type, and the True entity is 1 and the False entity is 0. Thank you @shiracamus.

python


print(bool(""))   # => False
print(bool("a"))  # => True
print(bool(1))    # => True
print(bool(0))    # => False
print(bool(None)) # => False
print(bool([]))   # => False
print(bool(()))   # => False
print(bool([0]))  # => True
print(not True)   # => False

That's all for this time. Now that you know the basic types of python. Next, let's organize the collection types.

Recommended Posts

Organize types in Python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
Read DXF in python
Daily AtCoder # 53 in Python
Use config.ini in Python
Daily AtCoder # 33 in Python
Solve ABC168D in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Simple gRPC in Python
Daily AtCoder # 24 in Python
Solve ABC167-D in Python