☆☆ 新着記事 ☆☆

2018年10月26日金曜日

Bootsrapで作るシンプル 2カラム・レイアウト コードサンプル


1. 基本の2カラム


<div class="bg-light">
    <main role="main" class="container" style="padding: 0px">

  <div class="row ">
   <div class="col-md-8 bg-success"><!-- cod-8 メイン・セクション開始 -->
    <h1> <p class ='text-center'>◇Col-md-8</p></h1>
     <div class="content-section">
       <h1> <p class ='text-center'>content-section</p></h1>
     </div>
      one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three,

     <div class="content-section">
      one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three, 1,2,3,one, two, three,
     </div>
   
   </div>

   <div class="col-md-4 bg-warning">
    <ul class="list-group">
       <li class="list-group-item list-group-item-light">Latest Posts</li>
       <li class="list-group-item list-group-item-light">Announcements</li>
    </ul>
   </div><!-- col-md-4 終了-->
  </div><!-- Div row 終了-->
  </main>
 </div>










COL間にmarginは設定されていないことに注意。




・Bootstrap4 のカラム間のマージン(余白・ガター)は、paddingで指定されている。
 デフォルトでは、左右15px

.col-md-4{
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
   }

これを変更するのは、独自のCSSでClassを作成し、適用する。

(my_gutterで挟まれたcol-md-4クラスの左右のpaddingは、7px)
.my_gutter .col-md-4 { padding: 0 7px;}



例)
<div class="row my_gutter">
 <div class="col-md-4">
sample text etc.
</div>
</div>

汎用的に、
.row-10{ margin-left:-5px;  margin-right:-5px}
.row-10 >div{ padding-right:5px;  padding-left:5px}
という書き方もできる。


https://tonari-it.com/column-margin-control/

Bootstrapで作る、シンプルな2カラム・レイアウトの例です。


コード:
<!DOCTYPE html>

   <head>
  <!-- Required Meta Tag -->
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <title>Bootstrap 2 Colomun Template</title>


     <!-- From Bootstrap CDN Link -->

   <!-- Latest compiled and minified CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <!-- Optional theme -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

 <!-- Latest compiled and minified JavaScript -->
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  
    
     <style>
       .navbar{
         margin-bottom:0;
         border-radius:0;
       }
     </style>
   </head>

   <body>
     <nav class="navbar navbar-inverse">
       <div class="container">
         <!-- Brand and toggle get grouped for better mobile display -->
         <div class="navbar-header">
           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
             <span class="sr-only">Toggle navigation</span>
             <span class="icon-bar"></span>
             <span class="icon-bar"></span>
             <span class="icon-bar"></span>
           </button>
           <a class="navbar-brand" href="#">Bootstrap CheatSheet</a>
         </div>
         <!-- Collect the nav links, forms, and other content for toggling -->
         <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
           <ul class="nav navbar-nav">
             <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
             <li><a href="#">Link</a></li>
             <li class="dropdown">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
               <ul class="dropdown-menu">
                 <li><a href="#">Action</a></li>
                 <li><a href="#">Another action</a></li>
                 <li><a href="#">Something else here</a></li>
                 <li role="separator" class="divider"></li>
                 <li><a href="#">Separated link</a></li>
                 <li role="separator" class="divider"></li>
                 <li><a href="#">One more separated link</a></li>
               </ul>
             </li>
           </ul>
         </div><!-- /.navbar-collapse -->
       </div><!-- /.container-fluid -->
     </nav>
     <!-- JUMBOTRON -->
     <div class="jumbotron text-center">
       <div class="container">
         <h1>Welcome To My Website</h1>
         <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor</p>
         <a href="#" class="btn btn-primary">Read More</a>
       </div>
     </div>
 
  あいうえお
  <h1> Hello World h1 </h1>
  <h3> Hello World h3 </h3>
  <h6> Hello World h1 </h6>
  <p> Hello World h1 <p>
 
  <div class="Container"> <!--main 開始---->
  <h1>PC画面用(lg)の時は2分割する</h1>
   <div class="row">
    <div class="col-lg-8 skyblue">  <!-- 次例 col-sm-9 も参照 -->
    1 (8/12)
     <ul>
      <li>1. Main Content</li>
      <li>2. Main Content</li>
      <li>3. Main Content</li>
      <li>4. Main Content</li>
     </ul>

    </div>
    <div class="col-lg-4 pink>
    1 (4/12)
     <div class="panel panel-default">
      <ul>
       <li>1. Side Content</li>
       <li>2. Side Content</li>
       <li>3. Side Content</li>
       <li>4. Side Content</li>
      </ul>
     </div>
    </div>
   </div>
  </div> <!--Container Main 終了-->
 
  <div class="Container"><!--Container Footer 開始---->
   Footer Area
  </div><!--Container Footer 終了---->
 
  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
     <!-- Include all compiled plugins (below), or include individual files as needed -->
     <script src="js/bootstrap.min.js"></script>
   </body>
 </html>  

このフォーマットも良い。


<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Simple Two Columns</title>
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <!-- ナビゲーション -->
    <nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">ブログ</a>
        </div><!--/.navbar-header -->
       
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active">
              <a href="#">
                <span class="glyphicon glyphicon-home"></span> Home
              </a>
            </li>
            <li>
              <a href="#">
                <span class="glyphicon glyphicon-heart"></span> Mail
              </a>
            </li>
          </ul>
          <form action="" class="navbar-form navbar-right" role="search">
            <div class="form-group">
              <input type="text" id="quick-text" name="quick-text" class="form-control">
            </div>
            <button type="submit" class="btn btn-default">検索</button>
          </form>
        </div><!--/.nav-collapse -->
     
      </div><!-- /.container -->
    </nav><!-- ナビゲーション終わり -->
   
    <div class="container">
      <div class="row">

        <!-- メイン記事 -->

    <!--- Extra Small(Phones (<768px)) で12 Columns、 
       Small Device(Tablets (≥768px) )以上で9-Columns使用->

        <div class="col-xs-12 col-sm-9">  <!-- サイドバーとの整合性用-->





   <div class="panel panel-primary">
             <div class="panel-heading">
                <h2 class="panel-title">Main Contents</h2>
             </div>
             <div class="panel-body">
                <div class="row">
                   <div class="col-xs-12 col-sm-6">
                      <img src="http://www.mossymob.net/media/Youtube-channel-300x215.png" class="img-responsive">
                   </div>
                   <div class="col-xs-12 col-sm-6">
                    <p class="text-primary">カテゴリ名など</p>
                     <p class="text-primary">時間など</p>
                      <p class="text-primary">コメント数など</p>
                      <p class="text-primary">aaa</p>
                       <hr>
                     <a href="http://mossymob.net/blog/" target="_blank"" class="btn btn-primary btn-block btn-lg">Continue to read</a>
                        </div>
              </div>  <!-- "row" 終了 -->
            </div> <!-- "panel-body" 終了 -->
          </div><!-- "panel panel-primary" 終了 -->
        </div><!-- メイン記事終わり -->

        <!-- サイドバー -->

        <div class="col-xs-12 col-sm-3">

          <!-- リンク -->
          <ul class="list-group">
            <li class="list-group-item active text-center">Link </li>
            <li class="list-group-item">
              <a href="http://mossymob.net/blog/" target="_blank">リンクA</a>
            </li>
            <li class="list-group-item">
              <a href="#">リンクB</a>
            </li>
          </ul><!-- リンク終わり -->

          <!-- カテゴリー -->
          <ul class="list-group">
            <li class="list-group-item active text-center">カテゴリー </li>
            <li class="list-group-item">
              <a href="#">メインカテゴリ </a>
              <a class="pull-right" href="#sub1" data-toggle="collapse">
                <span class="caret"></span>
              </a>
            </li>
            <div class="collapse" id="sub1">
              <a href="#" class="list-group-item">sub Category</a>
              <a href="#" class="list-group-item">sub Category</a>
              <a href="#" class="list-group-item">sub Category</a>
            </div>
          </ul><!-- カテゴリー終わり -->
       
        </div><!-- サイドバー終わり -->
     
      </div><!-- /.row -->
   </div><!-- /.container -->

   <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </body>
</html>



(Output)

 
 
 
**Snippet Folder
 
<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
    {% if title %}
        <title>Flask Blog - {{ title }}</title>
    {% else %}
        <title>Flask Blog</title>
    {% endif %}
</head>

<body>
    <header class="site-header">
      <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
          <a class="navbar-brand mr-4" href="/">Flask Blog</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href="/">Home</a>
              <a class="nav-item nav-link" href="/about">About</a>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">
              <a class="nav-item nav-link" href="/login">Login</a>
              <a class="nav-item nav-link" href="/register">Register</a>
            </div>
          </div>
        </div>
      </nav>
    </header>

    <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% block content %}{% endblock %}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">Latest Posts</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
 
CSS
body {
  background: #fafafa;
  color: #333333;
  margin-top: 5rem;
}
h1, h2, h3, h4, h5, h6 {
  color: #444444;
}
.bg-steel {
  background-color: #5f788a;
}
.site-header .navbar-nav .nav-link {
  color: #cbd5db;
}
.site-header .navbar-nav .nav-link:hover {
  color: #ffffff;
}
.site-header .navbar-nav .nav-link.active {
  font-weight: 500;
}
.content-section {
  background: #ffffff;
  padding: 10px 20px;
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-bottom: 20px;
}
.article-title {
  color: #444444;
}
a.article-title:hover {
  color: #428bca;
  text-decoration: none;
}
.article-content {
  white-space: pre-line;
}
.article-img {
  height: 65px;
  width: 65px;
  margin-right: 16px;
}
.article-metadata {
  padding-bottom: 1px;
  margin-bottom: 4px;
  border-bottom: 1px solid #e3e3e3
}
.article-metadata a:hover {
  color: #333;
  text-decoration: none;
}
.article-svg {
  width: 25px;
  height: 25px;
  vertical-align: middle;
}
.account-img {
  height: 125px;
  width: 125px;
  margin-right: 20px;
  margin-bottom: 16px;
}
.account-heading {
  font-size: 2.5rem;
}
 
 
 
 


GoogleAdsense広告の表示 -Simplicity, Blogspot


◆広告コードの取得
Adsenseアカウントにログインして、コードを取得します。
自動広告と、それ以前のページ別広告のコードは同じです。



するとコードが記載された小さいウィンドウがポップアップしますので、
左下のSnippetボタンを押して、コピーします。

自動広告のコードは、設置する場所にペースト内にペーストするのではなくて(しても良いですが)、htmlの<head>タグ内に記載すれば良い性質のものです。


1) Simplicityに広告表示する。

♥ いつもの事ですが、子テーマを編集しましょう。 

右サイドバーから

外観 > テーマの編集

を選択し、右側に表示される 「header-insert.php」に

以下のような感じで貼り付けます。





貼り付け方

<?php endif; ?>
<?php //ログインユーザーも含めてカウントする場合は以下に挿入 ?>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>     (adsbygoogle = window.adsbygoogle || []).push({          google_ad_client: "ca-pub-xxxxxxxxxxxx",          enable_page_level_ads: true     });</script>



2) Blogspotに広告表示する。

こちらも簡単です。

左サイドバーからテーマを選択し(下記参照)、html の<head>タグ内にアドセンス・コードを貼り付けるだけです。

 
 
簡単ですね。
 
広告がPCでも、スマホでも表示されることを確認してみてください。




既存のアドセンス・アカウントに新しくサイトを登録する方法

複数のサイトでGoogle Adsenseで広告表示をしたい場合があると思いますが、
それぞれのサイトで別のAdsense Accountを作成することは禁止されていますね。

Your AdSense account can't be activated because you have two AdSense accounts

While reviewing your account, we notice that you have another AdSense account. In this case, you need to close your other account. After you've closed your other account, you may resume the activation process.


ですから、既存のアカウントに新しくサイトを追加する必要があります。


Google Adsenseに別のサイトを追加する。


1. Sign in to your AdSense account.
アドセンスアカウントにログイン

2. In the left navigation panel, click Settings.
左ナビから、「設定」をクリック。

3.Click My sites.
My Sitesを選択

4.対象サイトの追加
 ’+’で、登録したいURLを追加。

するとリストに登録され、右側にサイトのオーナーシップに関して、
Verified(確認済み), unverified(未確認)の表示されます。

今回は、既に新規サイトでGoogle Analyticsを使う為に、サイト・オーナーシップの確認を終わらせていた為、追加と同時に、Statusが"Verified"になっていました。

このステータスがVerifiedになっていないと、広告が表示されません。

尚、一度、アドセンスのアカウントの作成が済んでいると、新しいサイトの追加の為に再度、承認を得る必要はないそうです。
新しいサイトに広告コードを配置する場合、新たにアカウントを開設したり Google に連絡したりする必要はありません。アカウントが承認されている場合は、AdSense コードを新しいページに配置すると、アカウントに新しいサイトが自動的に関連付けられます。
Google Help より

Googleも賢くなっていますね~。

サイトに広告を表示させる。

上記のとおり、新しいサイトをアドセンス・アカウントに追加しましたが、

登録したサイトの1つ、blogger (blogspot)の「レイアウト」で「Google Adsenseガジェット」が
追加できません。

以下のメッセージ。
「AdSense ガジェットを設定するには、まず [収益] タブを開いて AdSense アカウントを設定する必要があります。」

でも、[収益] タブを開くと、

「アドセンス申し込み」ボタンが表示されるだけなので、クリックしてみると、

「このユーザーは AdSense アカウントを持っていません。メール アドレスが AdSense アカウントのアドレスと一致していることをご確認ください。新しいアカウントを作成した場合、表示されるまでに 24 時間ほどかかることがあります。 」

Googleがマンを持して、2018年10月からBloggerでもサポートを始めた自動広告。
AIでページに合わせた最適な "形式" の広告を表示させるというもの。

ページがクロールされるまで、広告が表示されなかったり、不安定になったりするそうです。

さて、賢いGoogleも、登録反映までに時間がかかるんですね?



(2019.8)


Create an ads.txt file for 3 sites
To prevent severe impact on revenue, download an ads.txt file then upload the file to the root level domain of each site:
* mossymob.net
* mycodingjp.blogspot.com
* weekendmoviereviewjp.blogspot.jp

It may take a few days for changes to update. If you’re using another ad network, remember to add the network to the ads.txt file. See the ads.txt guide for more details.

2018年10月25日木曜日

Blogger スマホにアドセンスを表示させる方法 -2018


はてブなどのブログ・プラットホームやWordPressなどと比べると、小技を使うのが大変なBloggerですが、スマホ用の広告表示は知ってしまえば、凄く簡単。

手順は次の通り。

1. テーマで「ブログで使用中」のテーマを変更します。

 モバイルテンプレートはカスタム選択に変更した後に以下の手順を実行。

2.アドセンス・コードの貼り付け
テーマのhtmlの編集画面を開いて、「CTRL+F」で以下を検索。

<div class="’post-header-line-1’/">

をテンプレートから探し出します。’post-header-lineで検索すると便利です。

2カ所あるので、1個目のすぐ下にアドセンスコードを貼付け。

(3.アドセンス・コードの形式を実態コードに変換)
「&lt;」→「&lt;」、「&gt;」→「&gt;」という様に変換します。

とガイドしてくれているサイトもありますが、今時、やらないで良くない?
ということでとりあえず、そのまま貼り付け。

!!やっぱり変換しなくて良かった。そのまま貼り付ければOK この手順は不要でした。!!
(4.今度はスマホの記事下に表示させる設定)
先ほどの下にいれた広告コードのすぐ下の<data:post .body="">を同じ様に
検索して探して、その下にアドセンスの広告コードを張ります。

!!これはPC表示の際に、サイドバーの広告が出るように設定していると、スマホの場合、自動で 記事下に広告が表示されるようになっているので(BloggerのAuto ad設定利用でレスポンシブ対応済み)、で不要でした。4もやらないことにします。!!

ということで、結果がこちら。



別のブログでやっている記事のスマホのスクリーンショットです。

「成功者からのメッセージ」というブログで、アメリカの起業家の心に残る発言を中心に紹介しています。 興味があったら見てみてください。

タイトルと本文の間にスマホ用の広告が挿入されました。

PCでは表示されません。

少し大きすぎるかとも思うし、広告に表示されているような悩みなんてないけど、、、

まあ、Google様を信じてよしとしましょう。


2018年10月22日月曜日

Bootsrap (CDN利用)を利用したFlaskファイルでデータを受け取る

flask bootstrapは、今回は使用しない。


前回のlayout.html (親テンプレート)に、以下のようにboostrapからコピー・ペースト

layout.html

<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">

    {% if title %}
        <title>Flask Blog - {{ title }}</title>
    {% else %}
        <title>Flask Blog</title>
    {% endif %}
</head>
<body>
    <header class="site-header">
      <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
          <a class="navbar-brand mr-4" href="/">Flask Blog</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href="/">Home</a>
              <a class="nav-item nav-link" href="/about">About</a>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">
              <a class="nav-item nav-link" href="/login">Login</a>
              <a class="nav-item nav-link" href="/register">Register</a>
            </div>
          </div>
        </div>
      </nav>
    </header>
    <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% block content %}{% endblock %}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">Latest Posts</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

Output



Flask / Jinja2 -Template Inheritance テンプレートの親テンプレート作成

Templatesフォルダ内の
sample01.htmlとsample02.html内の共通部分を別のテンプレートにひとまとめにする。

☆最初の記述
1) sample01.html
<html>
 <head>
  <meta charset="utf-8">
 
   {% if title %}
  <title> MossyMob Blog - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}


 </head>
 </body>
   {% for post in posts %}
  <h1>{{ post.Artist }} </h1>
  <p>Born in  {{ post.Birthday }}</p>
  <p> Title is {{post.Title}} released in {{ post.Year_Released  }}
    {% endfor %}
   
 </body>
 </html>

2) sample02.html

<html>
 <head>
  <meta charset="utf-8">
   {% if title %}
  <title> MossyMob - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}

 </head>
 </body>
 <p>Sample02 Page: About</p>
 </body>
 </html>


◆共通項を記述するファイルを作成
layout.html
<html>
 <head>
  <meta charset="utf-8">
   {% if title %}
  <title> MossyMob - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}

 </head>
 </body>
  {% block content %}   #child templateがover wrightできるブロックを作成。


      {% endblock %}

 </body></html>

☆最初の記述
1) sample01.html

<html>   #共通部分を削除
 <head>
  <meta charset="utf-8">
   {% if title %}
  <title> MossyMob Blog - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}
 </head>
 </body>

 {% extends "layout.html" %}   #layout.htmlを適用する指定
 {% block content %}       #over wrightする箇所を指定
   {% for post in posts %}
  <h1>{{ post.Artist }} </h1>
  <p>Born in  {{ post.Birthday }}</p>
  <p> Title is {{post.Title}} released in {{ post.Year_Released  }}
    {% endfor %}
    {% endblock content %}  #blockに名前(今回はcontentという名前)を付けて終了することも可能。
   
 </body>
 </html>


2) sample02.html

<html>
 <head>
  <meta charset="utf-8">
   {% if title %}
  <title> MossyMob - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}
 
 </head>
 <body>
{% extends "layout.html" %}   #layout.htmlを適用する指定
 {% block content %}       #over wrightする箇所を指定

     <p>Sample02 Page: About</p>

    {% endblock content %}  #blockに名前(今回はcontentという名前)を付けて終了することも可能。

 </body>
 </html>


Outputのソースを表示すると以下のようにhtml構文が記述されている。

sample01.html

<html>
 <head>
  <meta charset="utf-8">
  <title> MossyMob Blog</title>

 </head>

 <body>
       
  <h1>Justin Bieber </h1>
  <p>Born in  March 1, 1994</p>
  <p> Title is Sorry released in 2016
   
  <h1>Taylor Swift </h1>
  <p>Born in  December 13, 1989</p>
  <p> Title is We Are Never Ever Getting Back Together released in 2012

 </body>
</html>

Flask/Jinja 2 if else in templates =テンプレート内でのIf elseの書き方


This is how to describe if else statements in Jinja 2 Template
Jinja 2 テンプレート内でのIf Else ステートメントの記述の仕方

========================================

Directory 構成

----
 |--- test01.py
 |---/templates
          |
          |--- sample01.html
          |--- sample02.html


1. test01.py

from flask import Flask, render_template
app = Flask(__name__)
post_data =[
  {
    'Artist':'Justin Bieber',
    'Birthday':'March 1, 1994',
    'Title': 'Sorry',
    'Year_Released':'2016'
    },
  {
    'Artist':'Taylor Swift',
    'Birthday':'December 13, 1989',
    'Title': 'We Are Never Ever Getting Back Together',
    'Year_Released':'2012'
    }
  ]
@app.route('/')
@app.route('/home')
def home():

    return render_template("sample01.html", posts=post_data)
@app.route('/about')
def about():
  return render_template("sample02.html", title="About")
if __name__ == '__main__':
    app.run(debug=True)


2. sample01.text
<html>
 <head>
  <meta charset="utf-8">

 {% if title %}
 <title>MossyMob Blog - {{ title }}</title> #titleが指定されていればtitleの値を表示
 {% else %}
 title>MossyMob Blog</title>
 {% endif %}
 </head>
 </body>
   {% for post in posts %}
  <h1>{{ post.Artist }} </h1>
  <p>Born in  {{ post.Birthday }}</p>
  <p> Title is {{post.Title}} released in {{ post.Year_Released  }}
    {% endfor %}

 </body>
 </html>

3.sample02.html
<html>
 <head>
  <meta charset="utf-8">
   {% if title %}
  <title> MossyMob - {{ title }}</title>
 {% else %}
  <title> MossyMob Blog</title>
 {% endif %}

 </head>
 </body>
 <p>Sample02 Page: About</p>
 </body>
 </html>


2018年10月16日火曜日

Python 配列(List, Tupple, Dictionary, Set)と要素へのアクセス

Pythonのリスト、タプル、ディクショナリ、セットについて、まとめておきます。
便利な使い方も忘れないように残しておきます、


1) リストは [ ] (角括弧)を使用します。任意の数の要素を代入でき、作成後、要素の追加や削除ができます。

2) タプルは ( ) (括弧)を使用します。任意の数の要素を代入できますが作成後、要素の追加や削除ができません。

3) ディクショナリは { } (波括弧)を使用します。任意の数の要素を代入でき、作成後、要素の追加や削除ができます。keyとvalueの2つで1つの要素という考え方で、1つのディクショナリの中で同じkeyを使用することができません。

4) セットは { } (波括弧)を使用します。任意の数の要素を代入でき、作成後、要素の追加や削除ができます。1つのセットの中で重複した要素を使用することができません。


具体例です。

Python Object -- Excelで管理する典型的表形式に対応する



1)リスト
定義:
name =["Justin", "Charlie", "Ed"]

    ◆追加
    name.append("Selena")

    ◆挿入
  name.insert(2, "Bob")
     >>> name = ['Justine', 'Ed', 'Serena']
     >>> name.insert(2, 'Bob')
     >>> name
     ['Justine', 'Ed', 'Bob', 'Serena']


*While文を使った例

fruits =['apple','orange','pineapple', 'banana', 'orange']
while fruits.count('orange'):  
*Listのcount methodは、引数に指定した値と同じ要素があれば、
 その数だけ繰り返す。
     fruits.remove('orange')

output: fruits =['apple','pineapple', 'banana']

*内包表記
number = []
for x in range(10):
    number.append(x)
print(number)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> number =[ x for x in range(10)]
>>> print(number)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


3) ディクショナリ



**Python3 では、dictionaryの順番は保持されます

*************************************************
people_string={
    "people":[
        {"name":"Wayne Rigsby",
         "phone":"123-456-789",
         "emails":["wayne@cbi.com", "wayne2@cbi.com"],
         "has_license":"true"},
        {"name":"Patric Jane",
         "phone":"987-654-321",
         "emails":"null",
         "has_license":"false"}
        ]
    }

for person in people_string[ "people"]:
    print(person)
{'name': 'Wayne Rigsby', 'phone': '123-456-789', 'emails': ['wayne@cbi.com', 'wayne2@cbi.com'], 'has_license': 'true'}
{'name': 'Patric Jane', 'phone': '987-654-321', 'emails': 'null', 'has_license': 'false'}

for person in people_string[ "people"]:
    print(person.keys())
dict_keys(['name', 'phone', 'emails', 'has_license'])
dict_keys(['name', 'phone', 'emails', 'has_license'])

for person in people_string[ "people"]:
    print(person.values())
dict_values(['Wayne Rigsby', '123-456-789', ['wayne@cbi.com', 'wayne2@cbi.com'], 'true'])
dict_values(['Patric Jane', '987-654-321', 'null', 'false'])

for person in people_string[ "people"]:
    print(person["name"])
Wayne Rigsby
Patric Jane

*************************************************
a={'name':'Freddie', 'song':'Rock you', 'year': '1977'}

要素へのアクセス

*valueには直接アクセスできないので、'key' を使ってアクセス。

print(a['name']) #Freddie
print(a['song'])   #Rock you
print(a['year'])   #1977

(Output)
print(a)                 #{'name': 'Freddie', 'song': 'Rock you', 'year': '1977'}
print(a.keys())      #dict_keys(['name', 'song', 'year'])
print(a.values())   #dict_values(['Freddie', 'Rock you', '1977'])
print(a.items())    #dict_items([('name', 'Freddie'), ('song', 'Rock you'), ('year', '1977')])

/// keyの一覧をプリントアウト
print('-------1')
for k in a.keys():
    print(k)
-------1
name
song
year

/// keyに対応するValueをプリントアウト
print('-------2')
for k in a.keys():
    print(a[k])
-------2
Freddie
Rock you
1977

print('-------3')
for v in a.values():
    print(v)  
-------3
Freddie
Rock you
1977

print('-------4')
for k, v in a.items():
    print(k, v)

-------4
name Freddie
song Rock you
year 1977

要素の追加

a['country']="U.K"

Output)
{'name': 'Freddie', 'song': 'Rock you', 'year': '1977', 'country': 'U.K'}

Keyを指定して要素の削除



*多元 Dictionary (辞書の要素にリスト)

a={'name': 'Freddie', 'song': 'Rock you', 'year': ['1977','1987','1997']}

(一気に個別の変数に代入)
a1, a2, a3 =a["year"] 
print(a1,a2,a3) #output 1977 1987 1997
b=a["year"]
print(b) #['1977', '1987', '1997']

*多元 リスト (リストの中に辞書)
a = [{'techacademy': 10}, {'online': 20}, {'programming': 30}]

print(a)             # Output : [{'techacademy': 10}, {'online': 20}, {'programming': 30}]
print(a.keys())  # Output : print(a.keys())
AttributeError: 'list' object has no attribute 'keys'
*リストの中に辞書が入ってしまうとkey functionではキーが抽出できない。


*多元 Dictionary (辞書の中に辞書)

a = { 'name' : {'First' : 'Charlie' , 'Last' : 'Puth'}, 'age' :24}

要素へのアクセス
>>> a['name']['Last']
'Puth'

要素のValueの変更
>>> a['name']['Last'] = 'Sheen'
>>> print(a)
{'name': {'First': 'Charlie', 'Last': 'Sheen'}, 'age': 24}


要素の追加
>>> a['name']['middle'] = 'Jake'
>>> a
{'name': {'First': 'Charlie', 'Last': 'Shean', 'middle': 'Jake'}, 'age': 24}

要素の削除
>>> del a['name']['middle']
>>> a
{'name': {'First': 'Charlie', 'Last': 'Shean'}, 'age': 24}

追加 (辞書同士の連結(結合))
>>> a ={'1':{'name': {'First': 'Charlie', 'Last': 'Puth'}, 'age': 24}}
>>> b ={'2':{'name': {'First': 'Ed', 'Last': 'Sheeran'}, 'age': 32}}
>>> a
{'1': {'name': {'First': 'Charlie', 'Last': 'Puth'}, 'age': 24}}
>>> b
{'2': {'name': {'First': 'Ed', 'Last': 'Sheeran'}, 'age': 32}}
>>> a.update(b)
>>> a
{'1': {'name': {'First': 'Charlie', 'Last': 'Puth'}, 'age': 24}, '2': {'name': {
'First': 'Ed', 'Last': 'Sheeran'}, 'age': 32}}

>>> a['2']['name']['Last']
'Sheeran'
>>> a['2']['age']
32


(dictionary型はappendは出来ない)
>>> a.append( { 'name' : {'First' : 'Ed' , 'Last' : 'Sheeran'}, 'age':32})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'

*内包表記
>>> map = { x : x**2 for x in (2,4,6)} ♯(2,4,6)は、キーとなるタプル
>>> print(map)
{2: 4, 4: 16, 6: 36}

*インデックス番号と要素を取り出す

enumerate 関数の引数を入力する辞書に items メソッドを組み合わせると、インデックス番号と値を取り出します。

>>> dict = {"tip":"orange","quiz":"orange is ?", "option":"orange1?",   "answer":"orange"}
>>> for index, value in enumerate (dict.items()):
...     print(f"{index}:{value}")
...
0:('tip', 'orange')
1:('quiz', 'orange is ?')
2:('option', 'orange1?')
3:('answer', 'orange')

*List形式のデータのインデックス番号を取得する場合は、.items()は不要。
for index, value in enumerate(data):
    print(f"{index}:{value}")


*後からDictionaryにリスト型で要素を追加
new_dict={}
new_dict["first_name"]=[]
new_dict["last_name"]=[]

new_dict["first_name"].append('Barak')
new_dict["first_name"].append('Michelle')
new_dict["last_name"].append('Obama')

print(new_dict)          #Output:{'first_name': ['Barak', 'Michelle'], 'last_name': ['Obama']}
print(new_dict["first_name"])   #Output:['Barak', 'Michelle']
print(new_dict["last_name"])   #Output:['Barak', 'Michelle']

Python random function の使い方 - randint, choice(), shuffle()


◇ ランダムな数字のリストを作成
list1 = [random.randint(0,99) for i in range(10)]
list2 = [random.randint(100,199) for i in range(10)]
list3 = [random.randint(200,299) for i in range(10)]

print(list1)
print(list2)
print(list3)

[42, 0, 98, 45, 43, 34, 55, 85, 95, 98]                                                
[133, 123, 101, 197, 114, 130, 142, 192, 146, 187]                                     
[268, 223, 284, 201, 286, 223, 228, 230, 288, 218]          


◆リストとランダム

choice()は要素を一つ取得、sample(), choices()は複数の要素をリストで取得できる。
sample()は重複なしの非復元抽出、choices()は重複ありの復元抽出。

random is giji ransu being created by the system clock.
Therefore, if system clock provides the same time, random will also create same order of numbers,.


sample of random func.

import random
list = [1,2,3,4,5,6,7,8,9,10]
random_l = random.sample(list,len(list))
print("Content-type: text/html\n")
print("<html><body>")
print(random_l)
print("</body></html>")

◆辞書型(dictionary)のシャッフル

◇keyを指定して、要素(Value)を並べ替える

from random import shuffle

questions = {
'1': {'tip': '1', 'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']},
'2': {'tip': '2', 'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
'3': {'tip': '3', 'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']},
'4': {'tip': '4', 'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
'5': {'tip': '5', 'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']}}
for item in questions.keys():
  shuffle(questions[item]['options']) 

print(questions)

{'1': {'tip': '1', 'answer': '1', 'question': '1?', 'options': ['3', '1', '2', '4']},
  '2': {'tip': '2', 'answer': '2', 'question': '2?', 'options': ['3', '2', '1', '4']},
  '3': {'tip': '3', 'answer': '3', 'question': '3?', 'options': ['4', '3', '1', '2']},
  '4': {'tip': '4', 'answer': '4', 'question': '4?', 'options': ['1', '4', '2', '3']},
  '5': {'tip': '5', 'answer': '5', 'question': '5?', 'options': ['4', '3', '1', '2']}}


◇関数を利用して順番を並べかえる

#1 パッケージのインポート
import random

#2 適当な辞書型(dict型)オブジェクトの作成
family = {
  "sazae":"サザエ",
  "katsuo":"カツオ",
  "masuo":"マスオ",
  "tara":"タラ",
  "hune":"フネ",
  "wakame":"ワカメ",
  "namihei":"波平",
  "tama":"タマ"
};
#3 辞書型オブジェクトをシャッフルできるメソッド
def shuffleDict(d):
  keys = list(d.keys())  <- Keyを取得してリスト化
  random.shuffle(keys) <- リスト化したkeyをシャッフル
  [(key, d[key]) for key in keys]
  random.shuffle(keys)
  [(key, d[key]) for key in keys]
  random.shuffle(keys)
  keys = [(key, d[key]) for key in keys]
  #keys = d(keys)
  return dict(keys)

#4 元の辞書型オブジェクト
print(family)

#5 シャッフル後の辞書型オブジェクト
print(shuffleDict(family))
{'katsuo': 'カツオ', 'wakame': 'ワカメ', 'masuo': 'マスオ', 'namihei': '波平', 'tara': 'タラ', 'hune': 'フネ', 'tama': 'タマ', 'sazae': 'サザエ'}

(使用例で確認)
import random
questions = {
 '1': {'tip': '1', 'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']},
 '2': {'tip': '2', 'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
 '3': {'tip': '3', 'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']},
 '4': {'tip': '4', 'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
 '5': {'tip': '5', 'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']}}
def shuffleDict(d):
   keys = list(d.keys())
   random.shuffle(keys)
   [(key, d[key]) for key in keys]
   random.shuffle(keys)
   [(key, d[key]) for key in keys]
   random.shuffle(keys)
   keys = [(key, d[key]) for key in keys]
   #keys = d(keys)
   return dict(keys)
 
print(shuffleDict(questions))

{
'5': {'tip': '5', 'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']},
'3': {'tip': '3', 'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']},
'4': {'tip': '4', 'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
'2': {'tip': '2', 'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
'1': {'tip': '1', 'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']}
}

*これでも良いのだが、keyの値を1とか2とか指定して要素にアクセスすると、結局、
 1~5までソートされた順列になってしまう

そこで、ランダムに要素を先にシャッフルした後で、keyとなる '1' ~'5' のインデックス番号は、
enumerate関数で後からつける。

*coding 例
import random

questions = (  ←この段階ではリスト
{'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']},
{'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
{'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']},
{'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
{'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']
 )
   
keys = range(len(questions))

random_q=()

random_q = random.sample(questions,len(questions)) ←リストのランダム
print(random_q)
#output
[
{'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
{'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']},
{'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']},
{'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
{'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']}
]

random_q2={}
random_q2=dict(list(enumerate(random_q,start=1)))←辞書型にしてインデックス番号付与
print(random_q2)
    
#output
#{
# 1: {'answer': '4', 'question': '4?', 'options': ['1', '2', '3', '4']},
# 2: {'answer': '5', 'question': '5?', 'options': ['1', '2', '3', '4']},
# 3: {'answer': '1', 'question': '1?', 'options': ['1', '2', '3', '4']},
# 4: {'answer': '2', 'question': '2?', 'options': ['1', '2', '3', '4']},
# 5: {'answer': '3', 'question': '3?', 'options': ['1', '2', '3', '4']}
# }




◇参考
>>> import random >>> d = {1:2, 3:4, 5:6, 7:8, 9:10}
>>> d {1: 2, 3: 4, 9: 10, 5: 6, 7: 8}
>>> keys = list(d.keys()) # Python 3; use keys = d.keys() in Python 2
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys] [(1, 2), (5, 6), (7, 8), (9, 10), (3, 4)]
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys] [(9, 10), (3, 4), (1, 2), (7, 8), (5, 6)]
>>> random.shuffle(keys) >>> [(key, d[key]) for key in keys] [(1, 2), (7, 8), (3, 4), (5, 6), (9, 10)]

Python localhost(html) へのprintout まとめ


表示させるpyファイル ==共通==
ファイル名: test.py

print("Content-type: text/html\n")
print("<html><body>Python is Fabulous !</body></html>")

A.上手く表示される場合
(1). Directory構成
---test/
 |
 |---cgi-bin/
          |
          |--- test.py

(a) cmd コマンド:
     test directoryにて
     test>python -m http.server 8000 --cgi
     localhost:8000/cgi-bin/test.py



4.上手く表示できない
(1). Directory構成
---test/
 |--test.py
 |---cgi-bin/
          |
         

(2) cmd コマンド:
     test directoryにて
     test>python -m http.server 8000
     localhost:8000/test.py


技法1:
answer1 = 50
answer2 = 100
print('答え1:{0}, 答え2:{1}'.format(answer1, answer2))

技法2:
answer = 50
print('答え:%d' % answer)


これらを使って、こんな愚直な書き方が出来る。

ファイル名:test.py


list = ['Tuna','Bacon','Burger','Tacos']

love = list[2]
hate = list[0]

print("Content-type: text/html\n")
print("<html><body>Python is Fabulous !<br/>")
print("Food I Love: {0}, Food I hate:{1}".format(love,hate))
print("</body></html>")

Output)
  Python is Fabulous !
  Food I Love: Burger, Food I hate:Tuna

◆文字型、数値型混在表記

print("Content-type: text/html\n")
print("""
      <html><body>
      This is web site made by Python!
      <p>This is easy one!</p> """)
name = "ALice"
age = 25
print("name is " + name+"<br/>")

print("age is " + age+"<br/>")  # This doesn't work


print("age is " + str(age)+"<br/>")
print("name is " + name+" age is"+str(age)+"years old"+"<br/>")
print("<hr>")
print(f' name is {name}, age is {age} ')
print("""
      </body></html>
      """)

Python 3 コマンドライン 一覧 参照



py.ファイル

list =['Tuna', 'Bacon', 'Softcream', 'Hot Dog']

html_output +=  f '<p> There are {len(list)} items in the list that I like.</p> '