How can I convert a string to an int in Python?

前端 未结 8 1356
北恋
北恋 2020-11-27 21:35

The output I\'m getting for my little example app is the following:

Welcome to the Calculator!
Please choose what you\'d like to do:
0: Addition
1: Subtracti         


        
相关标签:
8条回答
  • 2020-11-27 22:27

    Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)

    def convert(str):
        try:
            base = 10  # default
            if ':' in str:
                sstr = str.split(':')
                base, str = int(sstr[0]), sstr[1]
            val = int(str, base)
        except ValueError:
            val = None
    
        return val
    
    val = convert(raw_input("Enter value:"))
    # 10     : Decimal
    # 16:a   : Hex, 10
    # 2:1010 : Binary, 10
    
    0 讨论(0)
  • 2020-11-27 22:32

    Don't use str() method directly in html instead use with y=x|string()

    <div class="row">
        {% for x in range(photo_upload_count) %}
            {% with y=x|string() %}
    
        <div col-md-4 >
            <div class="col-md-12">
                <div class="card card-primary "  style="border:1px solid #000">
                    <div class="card-body">
                        {% if data['profile_photo']!= None: %}
                            <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                        {% else: %}
                            <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                        {% endif %}
                    </div>
                    <div class="card-footer text-center">
                        <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                    </div>
                </div>
            </div>
        </div>
        {% endwith %}
        {% endfor %}
    </div>
    
    0 讨论(0)
提交回复
热议问题