Improving Code: Capitalizing the first and third letter of a string - python-3.x

This is the first time I am learning python. I have had two C programming classes during my undergraduate days (many years back). I usually understand basic algorithms, but struggle to write codes out.
Currently doing a course in UDEMY, and the problem requires us to capitalize the first and third letters of the string. I have written the code (took me a while) and it works, but I know it is not pretty.
Please note: Trying to code it without using the enumerate function.
def wordplay(text):
first = text[0:1] #isolate the first letter
third = text[2:3] #isolate the third letter
firstc = first.capitalize() #capitalize the first letter
thirdc = third.capitalize() #capitalize the third letter
changedword = firstc + text[1:2] + thirdc + text[3:] #change the first and third letter to capital in the string
print(changedword)
The code worked, but looking to improve my logic (without using enumerate)

Here is one option which uses the capitalize() function:
inp = "hello"
output = inp[0:2].capitalize() + inp[2:].capitalize()
print(output) # HeLlo
The idea here is to just capitalize two substrings, one for the first two letters and the other for the remainder of the string.

Related

A simple basic Python3 question which I don't Understand

Question:
Fill in the function body for the Python3 function longestWord (you should leave the function header as it appears).
The function takes a single input argument which we assume is a list of strings, with each string forming one English word. The output should be a word from the list which has the greatest number of letters.
You must use a for loop to write this function.
Answer:
def longestWord(listOfWords):
biggestWord = listOfWords[0]
biggestNum = len(biggestWord)
for word in listOfWords:
num = len(word)
if num>biggestNum:
biggestNum=num
biggestWord=word
return biggestWord
print(longestWord(["Hello", "Goodbye"]))
I understand the first three lines. It takes the first value in the list and saves the length of the word inputted. However i don't understand the rest of the code. How does it compare the two inputted words to output the longest one. What is num and word?. Thank you.
I'd like to inform you that this question is about Python3 and not C++. Anyways, what the code is doing is it's taking the first word and stores it in a variable called biggestWord. and storing the length of biggestWord in a variable called biggestNum. Then for each word in listOfWords, it stores the word in a variable called word and stroing the length of it in variable called num. Then it compares num and biggestNum. If the length of some word i.e. num is bigger than the biggest length up until now, i.e. biggestNum, then it puts num in biggestNum to indicate that that's the biggest number up until now. and puts word in biggestWord replacing the old word. Then it returns the word with the biggest length, i.e. biggestWord.

String Operations Confusion? ELI5

I'm extremely new to python and I have no idea why this code gives me this output. I tried searching around for an answer but couldn't find anything because I'm not sure what to search for.
An explain-like-I'm-5 explanation would be greatly appreciated
astring = "hello world"
print(astring[3:7:2])
This gives me : "l"
Also
astring = "hello world"
print(astring[3:7:3])
gives me : "lw"
I can't wrap my head around why.
This is string slicing in python.
Slicing is similar to regular string indexing, but it can return a just a section of a string.
Using two parameters in a slice, such as [a:b] will return a string of characters, starting at index a up to, but not including, index b.
For example:
"abcdefg"[2:6] would return "cdef"
Using three parameters performs a similar function, but the slice will only return the character after a chosen gap. For example [2:6:2] will return every second character beginning at index 2, up to index 5.
ie "abcdefg"[2:6:2] will return ce, as it only counts every second character.
In your case, astring[3:7:3], the slice begins at index 3 (the second l) and moves forward the specified 3 characters (the third parameter) to w. It then stops at index 7, returning lw.
In fact when using only two parameters, the third defaults to 1, so astring[2:5] is the same as astring[2:5:1].
Python Central has some more detailed explanations of cutting and slicing strings in python.
I have a feeling you are over complicating this slightly.
Since the string astring is set statically you could more easily do the following:
# Sets the characters for the letters in the consistency of the word
letter-one = "h"
letter-two = "e"
letter-three = "l"
letter-four = "l"
letter-six = "o"
letter-7 = " "
letter-8 = "w"
letter-9 = "o"
letter-10 = "r"
letter11 = "l"
lettertwelve = "d"
# Tells the python which of the character letters that you want to have on the print screen
print(letter-three + letter-7 + letter-three)
This way its much more easily readable to human users and it should mitigate your error.

Cryptopals challenge 4 concern

i am not getting the desired results for Cryptopals challenge 4 set 1.
The concept of the program to check to see if any of these 300ish strings have been XORd by a single character. So with a brute force, my solution is take every string, XOR it with every character on the keyboard, and check to see if any of these results produce an english sentence. if not, then check the next string. Here is my code:
MY_DICT = {}
index = 0
my_plaintext = "Now that the party is jumping"
#fills the dictionary with hex strings from the txt file
with open("hexstrings.txt") as f:
my_list = f.readlines()
for x in my_list:
MY_DICT[index] = x.rstrip('\n')
index = index + 1
i=0
input() #this is just here to help me keep track of where i am when running it
#this loop fills possible_plaintext with all the possible 255 XORs of the i'th string
#of the dictionary that was previously filler from the txt file
for i in range(326):
possible_plaintexts = brute_force_singlechar_xor(MY_DICT[i])
print(possible_plaintexts)
if possible_plaintexts == my_plaintext: #line of concern
print("ya found it yay :) ")
Im sure that myBruteForce function works because it worked properly on the last problem where i XORd every possible char against a string. and i also know that the plaintext is the one provided bc i saw the solution. im just not sure why my program isnt recognizing that the plaintext is not in the dictionary.
(i am aware that using a scoring system to score every string to see if its close to english would be easier, but this is the way i chose to do it for now until i figure out how to get my scoring function to work /: )
How is your dictionary "possible_plaintexts" like when you print it?
Can you spot the solution in the printed text? How is it printed?
The decrypted string should also have a '\n' character.

Print First Letter of Each Word in a String in Python (Keep Punctuation Marks)

First post to site so I apologize if I do something wrong. I have looked for an appropriate answer, but could not find one.
I am new to python and have been playing around trying to take a long string (passage in a book,) and printing all but the first letter of each word while keeping the punctuation marks (Though not apostrophe marks.) and have been unsuccessful so far.
Example:
input = "Hello, I'm writing a sentence. (Though not a good one.)"
Code....
output = H, I W A S. (T N A G O.)
--Note the ",", ".", "()", but not the " ' ".
Any tips? Thank you all so much for taking the time to look
To help you on your adventure, I'll give you like a step-by-step logic of it
In python first use the .split() to seperate it by spaces
Go through each string in the list
Go through every char in the string
Print any punctuation marks that you specify and the first alphabetical character you find

Adding Hyphen within a spliced string

Continuing from my last question (which, btw, thanks for the help!), I'm stuck on how to add a hyphen to separate my string. Here's what I have so far:
original = "1234567890"
def fixPhoneNum(original):
original = list(original)
original[0], original[9] = original[9], original[0]
original[1:5], original[5:8] = original[5:8], original[1:5]
original = ''.join(original)
original = print(original[0:3], end="-"), print(original[3:7], end="-"), print(original[5:9])
return
Edit The above code doesn't give me the result I'm looking for
So basically, I took the original string of numbers, switched the first and last and the intermediary values with each other. Now I want to separate the first 3 digits, the next 3 digits with a hyphen.
Any help? This is driving me crazy.
Thanks!
I do not quite understand the rule for character ordering in your question.
Here is a simpler example of str.format function which accepts "0123" and produces "30-21" permutation with a hyphen. Hope it answers the question.
instr = "0123"
outstr = '{0[3]}{0[0]}-{0[2]}{0[1]}'.format(instr)
If you are not familiar with format strings, start with examples in the docs: https://docs.python.org/3/library/string.html#formatexamples

Resources