GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonprogramming.net — Python Programming Tutorials String Concatenation and Formatting Intermediate Python Tutorial part 2Welcome to part 2 of the intermediate Python programming tutorial series. In this part, we're going to talk about strings. Strange that we find such a topic in an intermediate series, but it's probably one of the most common things done improperly. To begin, recall that we have some major principles when it came to defining "intermediate" python. Two of them were that our code needs to be efficient and scale, and another was that others should be able to easily understand and use our code. These two principles come into contention when it comes to string operations. When concatenating strings, we can do the following: names = ['Jeff', 'Gary', 'Jill', 'Samantha']
for name in names:
statement = 'Hello there ' + name
print(statement)
Hello there Jeff Hello there Gary Hello there Jill Hello there Samantha This is easily read, but unfortunately not the ideal choice. Some people will conceed and let you do it if you're only adding two strings together, and that's it. Instead, you should be using names = ['Jeff', 'Gary', 'Jill', 'Samantha']
for name in names:
statement = ' '.join(['Hello there', name])
print(statement)
Hello there Jeff Hello there Gary Hello there Jill Hello there Samantha The reason for this is it scales better. When we use the names = ['Jeff', 'Gary', 'Jill', 'Samantha']
print(', '.join(names))
Jeff, Gary, Jill, Samantha Another fairly common string joining task is with file paths. It can be very tempting to do something like: /starting/file/path + '/' + filename As you may have guessed, this is not the correct method. Instead, we use # double back-slash for window's nonsense.
location_of_files = 'C:\\Users\\H\\Desktop\\Intermediate Python'
file_name = 'example.txt'
with open(os.path.join(location_of_files, file_name)) as f:
print(f.read())
Next, let's talk about string formatting. Let's consider that you want to insert variables into a string, like: ____ bought ____ apples today! ...where we want to fill in the blanks, with python variables: who = 'Gary' how_many = 12 So we want the sentence to be who = 'Gary'
how_many = 12
print('{} bought {} apples today!'.format(who, how_many))
There are more things we can do with string formatting, but I consider it to be beyond the scope of this series. For more information on strings, check out the strings docs That's enough on strings for now. Next, let's talk about the standard library: argparse, for adding command-line options to your Python programs.
|
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |