Showing posts with label stackoverflow goodies. Show all posts
Showing posts with label stackoverflow goodies. Show all posts

Saturday, April 7, 2012

Python: How to insert characters to the string at the end

Reference: http://stackoverflow.com/q/10059554/1276534
Credits: user1319219, Akavall, Mark Byers

Just in case you wondering what are the ways to insert character to the string at the front or back (beginning or end) of a string. Here are the ways to do it. Notice, string is immutable object, so you can not insert anymore characters into it. All we are doing is create a new string, and assign it to the variable. (That's why I did not use the same name, because I want to emphasize they are NOT the same string). But you can just as well use text = (any method)

# Create a new string that have 1 x in the beginning, and 2 x at the end
# So I want the string to look like this 'xHello Pythonxx'
text = 'Hello Python'

# Method 1, string concatenation
new_text = 'x' + text + 'xx'

# Method 2, create a new string with math operators
i = 1
j = 2
new_text = ('x'*i) + text + ('x'*j)

# Method 3, use the string's join() method
# You are actually joining the 3 part into a originally empty string
new_text = ''.join(('x', text, 'xx'))
And in case you don't trust me and want to see the output:
xHello Pythonxx
xHello Pythonxx
xHello Pythonxx

Python: How to find the integer and float in a string

Reference: http://stackoverflow.com/a/10059001/1276534
Credits: MellowFellow, hexparrot

If you have a string from somewhere, say a textbook, or an input. The string contain the data information you need. How do you extract the string? There are quite a few way to do it, range from hard code accessing it from index, to finding the E=, to using regular expression. In this example we will go over the middle of the range one. Because as beginner, it might not be the best idea to introduce regular expression yet. Plus this is the version I understand, maybe the regular expression version will be provided soon. (If you can't wait, you can check out from the reference link from above, there is the regular expression solution as well.)
# Assume you get this string from either a file or input from user
text_string = 'The voltage is E=500V and the current is I=6.5A'

# The starting index of this locating the voltage pattern
voltage_begin = text_string.find('E=')
# The ending index, note we are ending at 'V'
voltage_end = text_string.find('V', voltage_begin)

voltage_string = text_string[voltage_begin:voltage_end]
print(voltage_string, 'is at index:', voltage_begin, voltage_end)

#Since we know about the first to index is not useful to us
voltage_string = text_string[voltage_begin+2:voltage_end]

# So since now we have the exact string we want, we can cast it to an integer
voltage_as_int = int(voltage_string)
print(voltage_as_int)

Tuesday, April 3, 2012

Python Tkinter: How to set the window size without using canvas

Reference: http://stackoverflow.com/q/9996599/1276534
Credit: George, Bryan Oakley

Here is the code on how to set the window size without using canvas, it is great if you just starting, or do not want to use canvas to do this. You can specify your dimension in your frame, and then use pack_progate(0) flag to tell tkinter to use your size.
import tkinter as tk

root = tk.Tk()
frame = tk.Frame(root, width=400, height=400)
frame.pack_propagate(0) # set the flag to use the size
frame.pack() # remember to pack it or else it will not be pack

textBox = tk.Label(frame, text="(x,y): ")
textBox.pack()

root.mainloop()
Note: If your frame is not big enough to how the items, it will expand to fit your items). And the pack_progate(0) is a flag, it does not replace pack() method, you still have to call it or otherwise it will not appear. Hope this help.

Reference: stackoverflow 1, stackoverflow 2

Monday, April 2, 2012

Python: [] vs. {} vs. ()

Reference: http://stackoverflow.com/q/4407873/1276534
Authors: Zolomon, Greg Hewgill, Andrew Jaffe

It is a good note post to make sure we remember what is [] vs. {} vs. ()

() - tuple

A tuple is a sequence of items that can't be changed (immutable).

[] - list

A list is a sequence of items that can be changed (mutable).

{} - dictionary or set

A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).

Python: Regular Expression 101 Example Code

Reference: http://stackoverflow.com/q/9980381/1276534
Authors: Rajeev, George

In computer science theory class, we learned about regular expression. But it is unclear what exactly can it do at first, today I would like to introduce data validation as an example that uses the concept of regular expression. Python itself, like other language I assume (heard), has an implementation of regular expression. It comes standard from python too, see: http://docs.python.org/library/re.html

For example, you would like to ask the user for a telephone number, in the format of: 917-222-1234, if it is not in the format of XXX-XXX-XXXX, it will ask the user again until it is store. Let's take a look at the sample code.
import re

while True:
    # Get the user's input into the string
    myString = input('Enter your telephone number: ')
    
    # Matching it with the regular expresssion
    # isGoodTelephone will return True if it matches
    isGoodTelephone = re.match('^[0-9]{3}-[0-9]{3}-[0-9]{4}$', myString)
    
    if (isGoodTelephone):
        print('Great! Got your phone number into the system')
        print('Entry:', myString)
    else:
        print('Not in the correct format. Ex: xxx-xxx-xxxx')
    print()

Output of the csci133rep1.py:
Enter your telephone number: 917-123-1234
Great! Got your phone number into the system
Entry: 917-123-1234

Enter your telephone number: 9171231234
Not in the correct format. Ex: xxx-xxx-xxxx
Actually the basic of the regular expression is not too hard to learn, take a look at the bottom and you will able to figure out how to use it with no problem. Didn't need to put too much comment to make it understandable. Although there are much more ways to use it than just the telephone.
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
^       # mark the start of the telephone string
[0-9]   # any one of the 0123456789
{3}     # match it exactly three times, no less
-       # a hyphen symbol
[0-9]   # any one of the number between 0 and 9
{3}     # exactly three copies
-       # another hyphen symbol
[0-0]   # any one of the number 0-9
{4}     # four times
$       # mark the end of the telephone string