Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

'*' * length in place of for loop - where am I wrong?

I failed this Challenge Task as below: ... {% nam, dom = user.email.split('@',1) %} {% hid = nam[0] + ''(len(nam)-1) + '@' + dom %}' <div class="hidden name">{{ }}</div> ... I'm using '*'*length construct to hide the user name. The task asks to use a for-loop that I don't understand. Please help where I am wrong?

lunch.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    class User:
        email = None
    user = User()
    user.email = 'kenneth@teamtreehouse.com'
    return render_template('user.html', user=user)
templates/macro.html
{% macro hide_email(user) %}
  {% nam, dom = user.email.split('@',1) %}
  {% hid = nam[0] + '*'*(len(nam)-1) + '@' + dom %}
  <div class="hidden email">{{ hid }}</div>
{% endmacro %}

2 Answers

Justin Foss
PLUS
Justin Foss
Courses Plus Student 8,808 Points

Also if you haven't checked it out, i would definitely take a look at the jinja documentation. I was stumped on this all afternoon, so I finally dove into the docs. They're really clean and easy to understand, and not only was I able to solve the problem, but after just a little reading I understand Jinja2 a lot more.

Thanks! It works. Jinja2 looks like a python but not quite - lessons I learned.

Do look at some of the other answers to the macro question, Kenneth did a good job explaining.

  • you cannot use len() because Jinja2 barfs
  • for this string split, you need only the character on which you are splitting '@' and nothing more
  • rather than attempting to use * multiplied by len-1 (which, as I said, causes Jinja2 to barf), use a for loop like "for letter in nam[1:]" and have it print a * for each letter starting with slice at index 1
  • in order to declare nam and dom as variables you'll need a "with" declaration. This was just touched on in the "flash a message" unit of Flask Basics. Essentially, with enables you to call and set a variable for that instantiation only. It is one time and does not loop.

Like I said though, check out the one titled "Splitting the String" asked by Brandon Meredith it has this whole thing spelled out quite well. https://teamtreehouse.com/forum/splitting-the-string

Thanks! It works. Brandon's article was also helpful.