상세 컨텐츠

본문 제목

String Manipulation - example

Python

by techbard 2025. 3. 31. 19:08

본문

반응형
# text 파일의 내용을 리버스
# 1. 단어 내용을 리버스
# 2. 단어 순서를 리버스

# reverse words in a text file
import os
# os.path.join은 운영체제에 관계 없이 경로를 만들어 준다.
file_path = os.path.join('2025-03-10', '5 - example.txt')

reversed_words_letter = []
reversed_words_sequence = []

with open(file_path, 'r') as file:
    text = file.read()
    words = text.split()

    for word in words:
        reversed_words_letter.append(word[::-1])
    reversed_words_sequence = words[::-1]
        
print(reversed_words_letter)
print("=====================================")
print(reversed_words_sequence)

# Output
['stseroF', 'era', 'lativ',
=====================================
['generations.', 'future', 'for', 'ecosystems',

 

# Built-in string constants

# String processing is one of the more common tasks
# that today's programmers have to deal with.

import string

built-in constants for a variety of needs (pre-defined constants)
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.punctuation)

# output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

# # Define a test string
# test_string = "The quick brown fox jumps OVER the laze dog."

# use an iterator to see if a string contains any punctuation
if any(c in string.punctuation for c in test_string):
    print("The string contains punctuation.")
else:
    print("No punctuation found.")

# output
The string contains punctuation.

# generate a secure random password
alphabet = string.ascii_letters + string.digits + string.punctuation
import secrets
password = ''.join(secrets.choice(alphabet) for i in range(10))
print(password)

# output
%%o'?T%nw5

# Check the strength of a password
def check_password_strength(password):
    """ To keep things simple,
        we'll just assume that a password that
        has more than or equal to 10 letters,
        and has at least one character each of punctuation digits,
        and lower and uppercase letters is string. """
    if (len(password) >= 10 and
        any(char in string.punctuation for char in password) and
        any(char in string.digits for char in password) and
        any(char in string.ascii_letters for char in password)):
        return f"{password} is a string password."
    else:
        return f"{password} is a weak password."

print(check_password_strength("MyTestPa$$123!"))
print(check_password_strength("password"))
print(check_password_strength("pa$$w0rd!"))

# output
MyTestPa$$123! is a string password.
password is a weak password.
pa$$w0rd! is a weak password.

 

test_string = "The quick brown fox jumps OVER the lazy dog."

# Using find() to find the first occurrence of a substring. (remind: it's case sensitive)
print("First occurrence of 'the':", test_string.find('the'))

# Using index() to find the first occurrence of a substring (raises ValueError if not)
print("First occurrence of 'the':", test_string.index('the'))
try:
    print("First occurrence of 'fax':", test_string.index('fax'))
except ValueError as e:
    print(e)

# The 'in' operator can be used for Boolean testing.
print("Is 'fox' present:", "fox" in test_string)

# Using rfind() to find the last occeuuence of a substring.
print("Last occurrence of 'the':", test_string.rfind('the'))

# Using rindex() to find the last occeuuence of a substring (raises ValueError if not)
print("Last occurrence of 'jump':", test_string.rindex('jump'))

# replace() function will find content in the string and replace it.
# Now, one of the things to keep in mind is that, in Python,
# strings are immutable.
result = test_string.replace("lazy", "tired")
print(result)

# output
First occurrence of 'the': 31
First occurrence of 'the': 31
substring not found
Is 'fox' present: True
Last occurrence of 'the': 31
Last occurrence of 'jump': 20
The quick brown fox jumps OVER the tired dog.

 

# Manipulating string content

test_string = "The quick brown fox jumps OVER the lazy dog."

# upper, lower, title
print(test_string.upper())
print(test_string.lower())
print(test_string.title())

# output
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
the quick brown fox jumps over the lazy dog.
The Quick Brown Fox Jumps Over The Lazy Dog.

# strip, lstrip, rstrip
test_string2 = "   This string has whitespace   "

all_stripped_str = test_string2.strip()
print(test_string2.strip(), "len:", len(all_stripped_str))

left_stripped_str = test_string2.lstrip()
print(test_string2.lstrip(), "len:", len(left_stripped_str))

right_strriped_str = test_string2.rstrip()
print(test_string2.rstrip(), "len:", len(right_strriped_str))

# output
This string has whitespace len: 26
This string has whitespace    len: 29
   This string has whitespace len: 29

# split creates a sequence from a single string
words = test_string.split()
print(words)

# join concatenates ab iterable into a single string
say_hello = ["Hello", "world", "from", "Python"]
separator = " "
print(separator.join(say_hello))

# output
['The', 'quick', 'brown', 'fox', 'jumps', 'OVER', 'the', 'lazy', 'dog.']
Hello world from Python

 

# Formatting output strings

# Basic formatting - center(), ljust(), rjust()
# Python took care of the calculations of how long the string was
# and where to center it, or left, or right justify it in each one.
# width = 40

print("center".center(width, '-'))
print("left".ljust(width, '-'))
print("right".rjust(width, '-'))

# output
-----------------center-----------------
left------------------------------------
-----------------------------------right

# Formatting strings with format specification codes
val_1 = 1234.5678
val_2 = 10987.65
val_3 = 12.99
val_4 = -280.7

print(f"{val_1:.2f}")
print(f"{val_2:.2f}")
print(f"{val_3:.2f}")
print(f"{val_4:.2f}")

# output
1234.57
10987.65
12.99
-280.70


# Use alignment and width and leading zeros
print(f"{val_1:>10.2f}") # right align within 10 spaces
print(f"{val_2:>10.2f}")
print(f"{val_3:>10.2f}")
print(f"{val_4:>10.2f}")

# output
   1234.57
  10987.65
     12.99
   -280.70

# Use a grouping option and +/- signs
print(f"{val_1:>-10,.2f}")
print(f"{val_2:>-10,.2f}")
print(f"{val_3:>-10,.2f}")
print(f"{val_4:>-10,.2f}")

# ouput
  1,234.57
 10,987.65
     12.99
   -280.70

# Insert a fill character
print(f"{val_1:_>-10,.2f}")
print(f"{val_2:_>-10,.2f}")
print(f"{val_3:_>-10,.2f}")
print(f"{val_4:_>-10,.2f}")

# output
__1,234.57
_10,987.65
_____12.99
___-280.70

# Create format specifiers dynamically
format_spec = "{val:{width}.{precision}f}".format(val=val_2, width=10, precision=2)
print(format_spec)

# output
  10987.65

 

# String processing example

import string

def process_string(the_str, term):
    result = {
        "Punctuation": 0,
        "Whitespace": 0,
        "Uppercase": 0,
        "Lowercase": 0,
        "Found": False,
        "Index": -1
    }

    for char in the_str:
        if char in string.punctuation:
            result["Punctuation"] += 1
        elif char in string.whitespace:
            result["Whitespace"] += 1
        elif char in string.ascii_uppercase:
            result["Uppercase"] += 1
        elif char in string.ascii_lowercase:
            result["Lowercase"] += 1
    
    result["Index"] = the_str.upper().find(term.upper())
    result["Found"] = result["Index"] >= 0

    return result

test_string = "The quick, brows 'fox' jumps OVER the lazy dog."
search_term = "Fox"

result = process_string(test_string, search_term)
print(result)


# output
{'Punctuation': 4, 'Whitespace': 8, 'Uppercase': 5, 'Lowercase': 30, 'Found': True, 'Index': 18}
반응형

관련글 더보기

댓글 영역