Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Splitting the string

I am having issues with this. Specifically splitting the email string. I know how to split, but maybe I am losing something here.

If we just do split() on the email then we will get a list of the same string which is really no better than the start. The only real logical split character would be the '@' which would then just give us a list of two strings, which to me is about the same as where we started and then I'm getting lost on replacing characters in a range of a string etc.

Can anyone guide me to some resources, or one of the Python videos I can review to get my head wrapped around that.

I keep wanting to do list() on the email string, iterate over that replacing characters in a range with '*' then .join the list back together, but the challenge doesn't seem to like me doing that.

Thanks in advance for any guidance.

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) %}

  <div>
    {%
  </div>

6 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher
{% with name, domain = user.email.split('@') %}
    {{ name[0] }}{% for letter in name[1:] %}*{% endfor %}
{% endwith %}

I'll leave the rest for you to figure out.

Well, I knew I was over complicating it. I appreciate it, Kenneth

I would look out for U if I was checking out this tip to get help with this challenge. together with the hint from this https://teamtreehouse.com/forum/create-a-macro-hideemail post, and remembering that programming often can break when you are not case sensitive. :) (Hope I gave enough help, without giving away too much.)

So I can go over it again, when did you cover "with"?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

stuartholland every time we've shown flash messages in a Flask template, we've used with.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

It's kind of a two-step process. You have to split on the @, as you've done, then you need to step through the name part of the email starting at index 1. How do you get part of a string?

My bad for not clarifying a little more. I can get the slice etc. i.e

for i in email[0][1:]:

But trying a .replace throws errors about can't be integers, and some others I have run across while trying to figure this out.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

So don't replace. You have a slice and slices can be looped over with for loops, which you also have in templates.

Yup, drawing a blank on an alternative to .replace that would involve looping rather than concatination of slices and chars.

Going to go back through some earlier videos.

Sorry..still not getting it (at all).

But since Brandon seems satisfied I guess I'll just go back to reviewing Flask basics

and skip this course altogether.

Same here nothing is making sense

Kamilla Holanda Crozara
Kamilla Holanda Crozara
3,377 Points

Also works:

{% macro hide_email(user) %}
   {% set name, domain = user.email.split('@') %}
   {{ name[0] }}{% for c in name[1:] %}*{% endfor %}{{ "@" + domain }}
{% endmacro %}

Yes, I guess I guess I am over thinking this, but no, I don't really think you "brought it up in this course too".

Yes, this is challenging.

You said:

..you'll often be tasked with presenting information in an altered form. Sometimes you'll do the alteration in a view, sometimes in a model, and sometimes in a template or macro.

Actually I've done mostly front end stuff, so NO, I've never had to alter information on the back end (on the server)..at least up to now..


I think that sometimes people who work on server side languages (like python/ruby/php) forget there is a huge "leap" that has to be taken

in terms of development techniques when you get away from interacting with the browser directly.

I always test things on a local machine first before loading it up to the server.

The kind of things this course represents are totally happening remotely (out of sight).

I've done IT work where I've had to remote desktop onto a server, but in that case you can at least "pretend" you are interacting with a computer locally.

The whole running macros remotely and then having them eventually (in a very roundabout way) output into a browser is difficult to get my head around.


It sounds like Brandon eventually figured things out. (so I won't post any more in his thread).

I'm totally clueless how to answer this challenge..or in fact, most of the challenges in this course.

I guess I'll go back to Flask Basics (and maybe one of the beginning python courses).

The only thing interesting about Python for me is things like VPython and Pygames.

Definitely not macros.

Overall this whole subject matter is too abstract and obtuse..and frankly quite boring

It's basically using a text script to generate more text (with nary a hint of graphics involved).

It's like MS-DOS batch files, but on a server (using information gleaned from social media networking --raw computer networking is a lot more interesting to me than people networking).

The only reason I tried this course because it came up (in rather annoying fashion) on my Treehouse home page "dashboard",

(which has no "collapse" feature to hide courses you don't want to deal with)..


Some interesting things going on with servers:

Have you see the networked server setup for ALMA (Atacama Large Millimeter/submillimeter Array)?

There are also really interesting things happening with DNA/genome analysis:

http://www.ncbi.nlm.nih.gov/pmc/articles/PMC168966/

The server model.it creates 3D models of canonical or bent DNA starting from sequence data and presents the results in the form of a standard PDB file, directly viewable on the user's PC using any molecule manipulation program.


Anyway...maybe some hard core CLI jockeys find this "cutting edge", but after working with GPU hardware accelerated OpenGL and DirectX/XNA graphics for almost a decade,

it just seems a huge leap backward to have to "dumb down" output to simple text and primitive 2D graphics just to make it "social media friendly" and run on bandwidth constrained mobile devices running underpowered processors and not enough memory.

I've see huge advances in server technology over the last 15 years or so.

Not "cloud computing" (which is just server programming by a more hyped name), but virtualization technologies, the ability to handle "Big Data" through massively parallel distributed computing and even a few advances in artificial intelligence since MIT in the 1970's.

Technologies like augmented reality overlays and VR eye-wear (Oculus Rift, Microsoft HoloLens) are what I want to learn to output to (from a server),

not trying to design the next Facebook clone or "sharing" app (Uber/AirBNB/etc).

But I'm probably alone in thinking this, so I just leave off my "rant" right there.


The final word:

By the way, it turns out you don't really need a for..next loop to answer this challenge.

Instead you can use 'set'.

Want to know how?

A "mod" named "Dan Johnson" showed how,

(and gave some much better help on how to complete this challenge than Kenneth's 'hint'),

in this thread:

https://teamtreehouse.com/forum/create-a-macro-hideemail

Brandon,

Yes, strings in Python are immutable but variables that point to strings are mutable:

http://stackoverflow.com/questions/9097994/arent-python-strings-immutable

Oh..and I use the word 'variables' with some trepidation.

I think in Python variables are sometimes referred to as 'names' -- per this "Code Like a Pythonista" article:

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables


Kenneth,

<sigh>

You are giving me bad flashbacks to the nightmare that was your Regex course:

http://teamtreehouse.com/library/regular-expressions-in-python

.

The thing that throws me right off in this challenge's question is the word: "Print".

I'm thinking of the print to console command in python2 or the print() function in python 3.

However looking at the files in the download zip for the project,

there is code like this:

    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}

Is that what you are alluding to when you say "Print"?

Isn't 'render_field' a wtforms thing?

Reference:

http://flask.pocoo.org/docs/0.10/patterns/wtforms/#forms-in-templates


As to the "hint" code you posted in your first answer..

I'm guessing name[0] is treating the string "test" as a character array (after being split off before the '@' symbol in 'test@example.com').

So the zero index (splice?) represents the first character in the array - "t"

If so, then name[1] would be 'e' in the original 'test' -- that needs to be

changed/substituted/replaced with an asterisk (*)

After that I'm drawing a complete blank.

However, maybe some of these pages might be helpful/relevant for others:

https://mkaz.com/2012/10/10/python-string-format/

https://docs.python.org/2/library/stdtypes.html#string-formatting

http://www.pythoncentral.io/cutting-and-slicing-strings-in-python/

http://stackoverflow.com/questions/10017147/python-replace-characters-in-string

There is also something called "Jinja Templating" (which being part of a separate python-based Jinja2 templating engine, probably falls outside the scope of this course, but...) which also has some string formatting operations:

https://realpython.com/blog/python/primer-on-jinja-templating/


Please note, though, that the code answer the challenge is probably asking for (looking for as an answer) is definitely NOT AVAILABLE anywhere on the internet as an example/sample (AFAIK).

The closest web pages I could find (searching for Flask/Python examples that specifically used '.split('@')[0]') was:

A section of code in this tutorial:

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins

    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        user = User(nickname=nickname, email=resp.email)

This Github page:

https://github.com/peterhudec/authomatic/issues/54

..had this code snippet (spelling corrected):

            if user is None:
                nickname = automatic.result.user.name
                if nickname is None or nickname == "":
                    nickname = automatic.result.user.email.split('@')[0]
                nickname = User.make_unique_nickname(nickname)

Personally I think this challenge question sticks out like a sore thumb as not really being pertinant to the larger objectives of the course.

Code like this was not directly laid out (explained) in any of the videos I watched prior to this challenge.

I found no 'for...endfor' loop code that does character substitution in the download zip for the course.

Hopefully someone posts a stronger 'hint'...I'll bookmark this forum thread and check back later.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You are 100% overthinking this. The {{ tags are effectively print. We went over that in Flask Basics and I'm pretty sure I brought it up in this course too. So, yes, you're printing but, no, it doesn't require a console.

The rest of the work is splitting a string, printing the first character of part of the resulting list, printing an asterisk for the rest of that first member, then recreating the rest of the original string exactly as it was. There's no magic here and no trickery.

render_field is a macro that we made in this course. IIRC, it's actually the macro we made in the video directly preceding this challenge. So, no, it's not a wtforms thing.

Sorry if this is challenging. It's meant to be. And this is a very real world example as you'll often be tasked with presenting information in an altered form. Sometimes you'll do the alteration in a view, sometimes in a model, and sometimes in a template or macro. This happens to be a macro instance.

The last hint from Kenneth was all but a complete answer.

I feel silly now after solving the challenge as I wasn't thinking in the manner of Flask, but rather purely thinking Python.

Gavin Ralston
Gavin Ralston
28,770 Points

By the way, you can use the word 'variables' without 'trepidation' if you'd like. Eight-year-old articles on the internet notwithstanding. I've never really heard anyone calling variables "names" in practice.

For most peoples' purposes, variables change values, and they also change types, which, as you're probably fully aware, isn't always possible in every language.

Under the hood, though you're really looking at a reference to an object. Probably helpful to know at some point, but it's really hard to explain references and pointers sometimes, so people try really hard to come up with ways to explain them in plain English. Like "Hey, understand that the name you have there can reference...anything...and that those objects can exist still, but if we remove all references to them in our code, we can't get to them"