You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3

Click here for the last time

You will be an engineer in 100 days-Day 25-Python-Basics of Python language 2

String

I'm sorry if it doesn't appear

Of all the python data types, the string type is the most commonly used data type.

So let's take a closer look at how to handle string types.

** About character string type **

When making it a character string type Enclose in 'single quotes or " double quotes. The same applies when storing in a variable.

st = 'abcde'
print(st)
print(type(st))

abcde <class 'str'>

** Use single quotes and double quotes **

You can use ' in " ... " and " in'...'. To use "in"..."and'in'...' Use the \ backslash (\ in the Windows environment) to escape (disable) the quotes.

# \Backslashes can be used to invalidate and display subsequent quotes.
st = "We can use \" in the string."
print(st)

st = 'We can use \' in the string.'
print(st)

We can use " in the string. We can use ' in the string.

** Escape character **

Use this escape character when typing in a special string.

mac is \ backslash windows is a \ yen mark

You can express a line feed code by typing \ n, and a tab by typing \ t.

#Line feed code
print('aaaa \n bbbb')

#tab
print('cccc \t dddd')

aaaa bbbb cccc dddd

Line breaks are enter keys, but you can't type them in If you want to include a line break, you can express it using an escape character.

A specific character expressed using escape characters in this way It is called escape sequence.

There are some other escape sequences, You may not use it much.

** Mie quote **

Mie quotes " "" ... "" " and '''...''' are You can write a character string that spans multiple lines.

Triple quotes are often used as multi-line comments.

mail_text = '''
Hayashi

We become indebted to. I'm Kimori

Today we are pleased to announce the Welcome to the Jungle.
'''
print(mail_text)

Hayashi

We become indebted to. I'm Kimori

Today we are pleased to announce the Welcome to the Jungle.

This method is often used when creating mail merges. Prepare sentences in variables in advance By replacing some of them, you can create texts for various people.

** About string functions ** Python has various functions for manipulating strings.

Here are some of the most frequently used ones.

replace: Replace string Replacement target string.replace ('pre-replacement string','replacement string')

aaa = 'abcdefg'
print(aaa)
#Convert def to zzzz with replace
print(aaa.replace('def','zzzz'))

abcdefg abczzzzg

in , startswith , endswith Determines whether the target character string contains the search character string and returns a boolean value.

Search string in target string: Determine if the string is included Target string.startswith (search string): Determine if it is the starting string Target string.endswith (search string): Determine if it is a terminating string

apple = 'apple'
#Determine if apple contains pp
print('pp' in apple)

#Determine if apple starts with app
print(apple.startswith('app'))

#Determine if apple ends with le
print(apple.endswith('le'))

True True True

split , rsplit , splitlines : Convert strings to lists

String.split (separator): Separates strings based on the specified separator and returns a list

String.rsplit (delimiter, number of delimiters): Returns the direction from the opposite of split () to the specified argument

String.splitlines (): Separates the string at each newline and returns a list The list type will be described in detail in the next section.

# ,List type by delimiter
print('aaaa,bbb,ccc'.split(','))

#The direction to start separating is split()Returns from the opposite to the specified argument
print('aaaa,bbb,ccc'.rsplit(',',1)) 

#Separate the character string for each line break,Returns a list
print('aaaa\nbb\ncc'.splitlines())

['aaaa', 'bbb', 'ccc'] ['aaaa,bbb', 'ccc'] ['aaaa', 'bb', 'cc']

join() : Concatenate list-type strings in parentheses

'Delimiter'. join ([character, character])

aaa = ','.join(['a','b','c'])
print(aaa)

a,b,c

count() : Count the number of characters

Search target string.count (character string you want to count) Returns the number if found, 0 if not found.

aaa = 'Flat flat flat flat'.count('flat')
print(aaa)

aaa = 'Flat flat flat flat'.count('Rice')
print(aaa)

4 0

From here on down, I don't use it often It is provided as a string function.

find , rfind , index , rindex : Determine the position of the character string

Target string.find (search string): Finds the search string and returns the smallest index if found If not, return -1

Target string.rfind (search string)): Finds the search string and returns the largest index if found If not, return -1

Target string.index (search string): Finds the search string and returns the smallest index if found If not, an error is returned

Target string.rindex (search string): Finds the search string and returns the largest index if found If not, an error is returned

#Look for p from apple,If there is,Returns the smallest index.If not-Returns 1
print('apple'.find('p'))  

#Look for p from apple,If there is,Returns the largest index.If not-Returns 1
print('apple'.rfind('p')) 

#Find e from pen pine apple pen,If there is,Returns the smallest index
#If not, an error is returned
print('pen pine apple pen'.index('e'))  

#Search for e from pen pine apple pen,If there is,Returns the largest index
#If not, an error is returned
print('pen pine apple pen'.rindex('e')) 

1 2 1 16

isalnum , isalpha , isdigit , islower , isspace , istitle : Judgment of character string components

String.isalnum (): Determining if all characters are alphanumeric

String.isalpha (): Judgment whether all characters are alphabetic

String.isdigit (): Determining if all letters are numbers

String.islower (): Determining if all case-sensitive characters are lowercase

String.isspace (): Determining if all characters are blank

String.istitle (): Determining if the string is a title case (starting with an uppercase letter)

#Determine if the string is alphanumeric only
print('az189898ssss'.encode('utf-8').isalnum()) 

#Determine if all strings are alphabetic
print('aaaaAAAZZZzz'.encode('utf-8').isalpha()) 

#Determine if the string is just a number
print('123112399876'.encode('utf-8').isdigit()) 

#Determine if it's only lowercase
print('abcdefghijkl'.encode('utf-8').islower()) 

#Determine if a character is blank
print('            '.encode('utf-8').isspace()) 

#The string is the title case(Uppercase letter)Judgment of whether
print('Apple Zedd  '.encode('utf-8').istitle()) 

True True True True True True

capitalize , swapcase,title,lower,upper` : Uppercase / lowercase conversion

String.capitalize (): Uppercase only the first letter

String.swapcase (): Convert uppercase letters to lowercase letters and lowercase letters to uppercase letters

String.title (): Make the string a title case (capitalized at the beginning)

String.lower (): Convert all characters to lowercase

String.upper (): Convert all characters to uppercase

#Uppercase only the first letter
print('az189898ssss'.capitalize()) 

#Uppercase to lowercase,Convert lowercase letters to uppercase
print('az189898SSSS'.swapcase())   

#String title case(Uppercase letter)To
print('az189898ssss'.title())      

#Convert all characters to lowercase
print('Za189898SsSs'.lower())      

#Convert all characters to uppercase
print('az189898ssss'.upper()) 

Az189898ssss AZ189898ssss Az189898Ssss za189898ssss AZ189898SSSS

String format

I'm sorry if it doesn't appear

The previous section dealt with string functions. Among them, I often remember the part related to the format of the character string. I would like to go into detail.

Format is to control the output of strings

There are three ways to format a string.

Format by inserting a specific format character into the first character string. `` Use the second format function. `Use the third string type format function.

The second and third use the function for format, with only a slight difference in writing. It's almost the same.

** format How to format with characters **

'String% The symbol that the data to be merged corresponds to'% (variable)

% s: String type % d: Integer type % f: Decimal point type % x: Hexadecimal notation % o: Octal notation % %% d: If you want to add%

errmsg = "Can't open file"
errcode = 19042
#Insert the result of a variable into a string%s , %d
msg = "ERROR: %s (%d)" % (errmsg, errcode)
print(msg) 

ERROR: Can't open file (19042)

In the above example, with the normal print function Although string type data and numerical data cannot be handled together If the data is merged using format characters, it can be handled even if the data type is different.

String type in the part of % s Integer type data can be inserted in the part of % d.

#String type
print ("%s" % "ABC")
#Integer type
print ("%d" % 123)
#Decimal point type
print ("%f" % 1.23)
#Hexadecimal
print ("%x" % 255)
#Octal
print ("%o" % 255)
# %If you want to display
print ("%%%d" % 80)

ABC 123 1.230000 ff 377 %80

A convenient format is the number following%. You can specify the character width and the number of digits.

#=> |  ABC| :Right-justified 5 characters
print ("|%5s|"   % 'ABC')      

#=> |ABC  | :Left-justified 5 characters
print ("|%-5s|"  % 'ABC')      

#=> |  123| :Right-justified 5 digits
print ("|%5d|"   % 123)     

#=> |123  | :Left justified 5 digits
print ("|%-5d|"  % 123)        

#=> | +123| :± signed
print ("|%+5d|"  % 123)        

#=> | 1.23| :Total number of digits.Number of digits after the decimal point
print ("|%5.2f|" % 1.23)       

#=> |00123| :0 fill
print ("|%05d|"  % 123) 

| ABC| |ABC | | 123| |123 | | +123| | 1.23| |00123|

** How to use the format function **

format (data to be inserted, character string to be inserted)

Character string to insert .format (data to insert)

Personally, character string.format () is easier to use. This is the main explanation.

Add {} wave brackets to the character string to be inserted. Insert the characters in it.

aaa = 'Insert characters after this{}Plugged in'.format('Sashiko')
print(aaa)

Insert the characters after this

You can insert characters in the {} part.

Use the index to handle the insertion of multiple characters. {} The index numbers in the wave brackets correspond to the order in which they are placed in the format function.

#The first is 0, the second is 1, and the third data is 2.
print('{0}-{1}-{2}'.format('100', 'Two hundred', 300))

100-200-300

The first data is inserted in {0}, and the second data is inserted in {1}.

{} Specify any name in the wave brackets You can also enter it as a keyword argument.

#Enter the characters corresponding to each name
print('{year}Year{month}Month{day}Day'.format(year=2018, month=1, day=11))

January 11, 2018

The value of year = specified in the argument is inserted in {year}.

** Left justified, center justified, right justified **

You can left justify, center justify, and right justify with < ^ >. You can also specify the total number of characters as a number and specify the characters to fill. If omitted, it will be a space, and if it is one character, full-width characters are OK.

{: Number of digits of shift symbol} .format (number, etc.)

print('left  : {:<10}'.format(100))   #Left justified
print('center: {:^10}'.format(100))   #Centering
print('right : {:>10}'.format(100))   #Right justified

print('left  : {:*<10}'.format(100))  #Left justified
print('center: {:a^10}'.format(100))  #Centering
print('right : {:demon>10}'.format(100)) #Right justified

left : 100 center: 100 right : 100 left : 100******* center: aaa100aaaa right: Demon Demon Demon Demon Demon Demon 100

** Filled with 0 **

If you want to pad with zeros to match the number of digits Specify 0 to fill in and right justify.

{: 0 digits} .format (numerical value)

#Fill with 0 in 5 digits
print('zero padding: {:05}'.format(123))

zero padding: 00123

** Digit separator (comma, underscore) **

You can put a , comma or'_' underscore delimiter every 3 digits.

{:,} .format (numerical value) {: _} .format (numerical value) Note that the _ underscore is an option added in Python 3.6. It cannot be used if the version is old.

#Separated by commas
print('{:,}'.format(100000000))

# _Separated by 3 digits#print('{:_}'.format(100000000))
100,000,000

** Specify the number of digits after the decimal point **

To specify the total number of digits, write the number of digits after .. If it is below the decimal point, add f to represent a fixed-point number.

{:. Number of digits} .format (numerical value) {:. Number of digits f} .format (numerical value)

#Display up to 2 digits
print('{:.2}'.format(1.234321))
 #Display up to 5 digits
print('{:.5}'.format(21.23432))

#5 decimal places
print('{:.5f}'.format(221.234543))

1.2 21.234 221.23454

Arithmetic operator

I'm sorry if it doesn't appear

In programming languages, there are symbols and symbols that represent various operations. We call it an "operator".

If you divide it into four

  1. Arithmetic operator (algebra)
  2. Assignment operator
  3. Relational operator (comparison)
  4. Logical operators Will be.

This time, we will deal with "arithmetic operators".

** Arithmetic operator (or algebraic operator) **

Arithmetic operators are "operators" used to perform four arithmetic operations.

symbol meaning
+ Addition(addition))
- Subtraction(subtraction)
* Multiply(multiplication)
/ division(division)
% Surplus(remainder)
** Exponentiation

The + plus plus and the - minus minus are the same. The symbols that can be used change between multiplication and division.

Multiplication is * asterisk Division is / slash Other rare ones have a % remainder.

#addition(Addition)
1+2

#subtraction(Subtraction)
1-3

#Multiplication(Multiply)
2*3

#division(division)

10/3 3 2 6 3.3333333333333335

In Python3, if there is only one / slash, the result will be up to the decimal point.

If you want only integer values, double the // slashes. This will be truncation division.

#division(No remainder, truncation division)
10//3
#Exponentiation
2**3

You can also calculate routes using exponentiation symbols.

#root
print(2**0.5)
print(9**0.5)

1.4142135623730951 3.0

As a special calculation method, it is called a remainder. It is a method to find the remainder when broken.

Use the % symbol to find the remainder.

#Surplus(The remainder when broken)
print(5%3)
print(5%2)
print(5%5)

2 1 0

This calculation of the remainder can be done in various conditional branches in the program. It can be applied to judgment.

#The priority of multiplication and subtraction is the same as that of math
2 * 3 + 4

10

Use () parentheses if you want to prioritize addition and subtraction

a,b,c = 2,3,4
d = a * b + 4
e = a * (b + 4)
print(d)
print(e)

10 14

Since the four arithmetic operations are the basis of programming Make sure you remember how to write it.

Assignment operator

I'm sorry if it doesn't appear

In programming, storing data It is called "assignment".

The operator related to the assignment method is the "assignment operator".

Substitution is a = equal symbol.

When substituting characters, enclose them in 'single quotes or " double quotes. When substituting a number, enter the number as it is.

#Substitute the numerical value 121 for the variable a
a = 121
print(a)

121

"Assignment" is to the variable to the left of = equal It works like inserting the calculation result on the right side.

#Variable a,prepare b
a , b = 2 , 3
print(a)

# a = a +Same meaning as b
a += b
print(a)

2 5

The result of adding b to ʻa will be substituted into ʻa again. It has the same meaning as ʻa = a + b. The result is that ʻa contains 2 and b contains 3, so 2 + 3 Go inside ʻa`.

The method using this assignment operator is often used in programs. Especially, how to add the value of the variable by 1 with + = 1 It is used quite often.

About other "assignment operators"

a = b         #Substitute b for a
a += b        # a = a +Same as b
a -= b        # a = a -Same as b
a *= b        # a = a *Same as b
a /= b        # a = a /Same as b
a %= b        # a = a %Same as b
a **= b       # a = a **Same as b
a //= b       # a = a //Same as b

I added or subtracted the variable on the right to the variable on the left You can do things like substitute the result.

#Variable a,prepare b
a , b = 2 , 3

print(a)

#Try adding a few times
a += 2
a += 5
print(a)

2 9

The value of the variable changes each time it is assigned.

Since the contents of the variable change greatly with this one line Where and how the value is changed Let's hold down how to use operators so that you can understand them immediately.

Relational operator

I'm sorry if it doesn't appear

If there is only one = equal, the value will be stored by assignment.

If you use two == equals, this time it will be a movement to compare the left side and the right side.

There are multiple ways to compare, and there are multiple operators. Operators that make such comparisons are called relational operators and comparison operators.

** Comparison of numbers **

First, prepare the numerical data.

Prepare the variables ʻaandb`

a , b = 2 , 3

==: Determine if the left and right of the operator are equal If they are equal, True is returned, and if they are not equal, False is returned.

#Determining if a is equal to b
a == b

False

! =: Determine if the left and right of the operator are not equal If they are not equal, True is returned, and if they are not equal, False is returned.

#Determining if a is different from b
a != b

True

Compare if the left of the < operator is less than the right

True if the left side of the operator is less than (less than) the right side If not, False will be returned.

#a is less than b(Less than)Small
a < b

True

Compare if the left of the > operator is greater than the right

True if the left side of the operator is greater than the right side If not, False will be returned.

#a is greater than b
a > b

False

If you add = equal to more or less, it means above and below.

<=: If the left side of the operator is less than the right side, True is returned, otherwise False is returned.

#a is less than or equal to b
a <= b

True

> =: True is returned if the left side of the operator is greater than or equal to the right side, False is returned if not.

#a is greater than or equal to b.
a >= b

False

Operators that compare magnitudes are only for numerical calculations Because it cannot be used correctly Pay attention to the shape of the data stored in the variable.

** String comparison **

String comparison

ʻIs(determination of equality) not (denial) ʻIn (determination of inclusion)

Etc. are used.

If the judgment is correct, it returns True, and if it is not correct, it returns False.

a , b = 'a' , 'b'

#Determining if a is equal to b
print(a is b)           

#Determining if a is different from b
print(a is not b)       

#Determining if a is included in b
print(a in b)   

#Determining if a is not included in b
print(a not in b)

False True False True

In particular, the judgment of whether or not characters are included is often used.

Since the control of the program using the character search result comes out frequently. Let's hold down the method of comparison using the ʻin` operator.

Comparing letters and numbers like this The result will be returned as a True or False bool type.

How to control the program using the results of the comparison It is often used in programs, so remember how to write it.

Logical operator

I'm sorry if it doesn't appear

The "logical operator" returns the result of adding the comparison results together. This method is always used when combining several conditions.

There are only three logical operators.

and or not

and

ʻAndconnects conditions to conditions. In Japanese, it meansand`.

Condition A and Condition B

True if both conditions are True If either one is False, the result will be False.

Must meet both the left and right sides of ʻand It cannot beTrue`.

#Two conditions are True
print(True and True)

#One condition is False
print(True and False)
print(False and True)

#Both conditions are False
print(False and False)

True False False False

#Example with numeric type
print(1==1 and 2==2)
print(1==1 and 2==1)

True False

Judgment that meets multiple conditions such as men and people in their twenties Use it when you want to do it.

a , b = 20 , 'male'
print(a==20 and b == 'male')

True

or

Returns True if either the left or right side of ʻor is True. In Japanese, it means or`.

Condition A or Condition B

True if both are met If either one matches, True will be returned. False is returned only if both conditions are not met.

#Two conditions are True
print(True or True)

#One condition is False
print(True or False)
print(False or True)

#Both conditions are False
print(False or False)

True True True False

#If both conditions are met
a , b = 20 , 'male'
print(a==20 or b == 'male')

#If either condition is met
a , b = 20 , 'male'
print(a==30 or b == 'male')

#If both conditions are not met
a , b = 20 , 'male'
print(a==30 or b == 'Female')

True True False

not not has the meaning of denying and upsets the result.

Set True to False and False to True.

#When including
d = 'male'
print('Man'  in d)

True

#If you want not to be included
d = 'male'
print('Man'  not in d)

False

Control in the program is a combination of comparison and logical operators We will build up how to branch and continue the process. Also remember how to use logical operators.

** Summary of logical operations **

Logical operation result
True and True True
True and False False
False and True False
False and False False
True or True True
True or False True
False or True True
False or False False

Summary

Strings are the most common form of data in a program. Therefore, there are various operation methods.

When reading or writing data from a file Since input and output are performed as a character string The way you work with strings is pretty important.

All operators are related to the control of the program. Under what conditions, what value is returned, and how the result is Let's hold it down.

74 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 34 --Python --Python Exercise 3
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 74 ――Programming ――About scraping 5
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 76 ――Programming ――About machine learning
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 84 ――Programming ――About machine learning 9
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
The basics of running NoxPlayer in Python
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
How much do you know the basics of Python?
What beginners learned from the basics of variables in python
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
Will the day come when Python can have an except expression?
How to know the internal structure of an object in Python
For Python beginners. You may be confused if you don't know the general term of the programming language Collection.
Check the behavior of destructor in Python
[Fundamental Information Technology Engineer Examination] I wrote an algorithm for the maximum value of an array in Python.
If you want a singleton in python, think of the module as a singleton
The story of an error in PyOCR
[Python3] Understand the basics of Beautiful Soup
The story of making Python an exe
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Python Note: When you want to know the attributes of an object
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
I didn't know the basics of Python
The result of installing python in Anaconda
Open an Excel file in Python and color the map of Japan
In search of the fastest FizzBuzz in Python
Get a datetime instance at any time of the day in Python
An example of the answer to the reference question of the study session. In python.
[Python3] Understand the basics of file operations
An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it