QA Graphic

Working with Python Strings

Some Practical Examples

Python Strings

Various code snippets on using strings in Python.

Getting a File to a String

This is useful when you have a list in a file and you want to use it in your code. At the end of this snippet, I shuffle the new list.

f = open('~/random/content/namelist.txt', 'r');
surnames = f.read();
f.close();
surname = surnames.splitlines()
random.shuffle(surname)

Replacing different words with a single replacement

An easy way to search/replace multiple items:

# Quick Utility Function
def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text
# Sample String
story = "author was set to move to state"
# dictionary with mixed keys
my_dict = {'author': 'John', 'state': 'Massachusetts'}
newstory = replace_all(story, my_dict)
print(newstory)

Use the String as a List

What if I wanted the 3rd word in a particular string?

# Sample string
mytext = "Pleached Baloney Silurus Ramble Chemolytic Bidentate Malanders Brugnatellite"
# Use Split to break the string
newtext = mytext.split()
# Now display the third word, keeping in mind the counter starts at zero
print(newtext[2])

Counting the number of List Elements

thekeywords= ["sum", "fast", "snow", "Sawyer", "Pond"]
totallines = len(thekeywords)
print(totallines)

Looping through an List to output data

In this example, I am splitting up a string and shuffling the words:

import random
samplequote = "Today is gonna be the day that they're gonna throw it back to you"
samplequote2 = samplequote.lower().split()
random.shuffle(samplequote2)
# Create a function to display the Array, useful if you want to do something other than printing.
def print_list_elements(list):
    for element in list:
        print(element)
print_list_elements(samplequote2)
# Quick and Easy Way:
print("Really easy way:" + str(samplequote2))
# Show it as a new String, capitalize the first word in the sentence:
print(' '.join(samplequote2).capitalize() )