#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 7: string formatting and concatenation
0:00 Right, next stop: string formatting and concatenation. And pretty important because you will be doing this a lot in your code. It's funny the other day
0:08 I bought some clay with my daughter and we were making Python figures and obviously we were very bad at it
0:15 and then we got better. And I found it a nice analogy with string formatting. As the Zen says there's preferably one best way to do it
0:23 and there are various ways to do string formatting but in the end there is a best way which is now the f-string in 3.6
0:31 but if you're not on 3.6 then at least you can use format that's basically the gist for me of doing formatting
0:37 the right way. But let's also demo that with some code And I hope you agree that those last two figures were definitely better than the first.
0:44 Alright, total hours is six print. the course takes plus total hours to complete. Okay a type error, not good
1:02 so I cannot add an 'int' to a 'string' and vice versa. So I need to make this a string and then it works. But yeah, it's not the best way to do it.
1:13 And the best way is using f-strings in Python 3.6 and look at that I can just embed the variable. This can even take operations, its pretty awesome
1:29 but yeah, this is faster and it's much easier to read and I don't have to concatenate or even doing any type conversion.
1:36 So go with f-strings, but maybe you're not on 3.6 for some reason and then you can use format. So you would write this as in the same curly braces
1:53 and then you use format on that string and give it a variable. And you don't have to worry about type conversion because format is,
2:01 sorry, not using f-strings anymore format is smart enough to convert this 'int' into a 'string' or whatever is needed to make this work.
2:10 And then last note about concatenation so as said before, building up a string like this is not the way, and its slower
2:19 if you're working with a lot of data and how true is that, right? Every day you get to write Python is a happy day
2:28 but, it's not happy for your performance and readability I would say, it's not really looking nice in this case you really want to use join
2:38 so you want to really have your strings in a sequence or a list, and then just join them together and you can specify what to join on
2:47 and there you go, here's my same string as above but using the Pythonic way of joining and, you know, you can do what you want
2:55 you can also join it on dash, even better I can leave off the spaces here and give join a space. So I'm going from multiple spaces
3:06 or worry about spacing in the first place by doing that in one place at the join level so much better.