Adding Hyphen within a spliced string - python-3.x

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

Related

Improving Code: Capitalizing the first and third letter of a string

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.

Basic string slicing from indices

I will state the obvious that I am a beginner. I should also mention that I have been coding in Zybooks, which affects things. My textbook hasn't helped me much
I tried sub_lyric= rhyme_lyric[ : ]
Zybooks should be able to input an index number can get only that part of the sentence but my book doesnt explain how to do that. If it throws a [4:7] then it would output cow. Hopefully I have exolained everything well.
You need to set there:
sub_lyric = rhyme_lyric[start_index:end_index]
The string is as a sequence of characters and you can use string slicing to extract any sub-text from the main one. As you have observed:
sub_lyric = rhyme_lyric[:]
will copy the entire content of rhyme_lyric to sub_lyric.
To select only a portion of the text, specify the start_index (strings start with index 0) to end_index (not included).
sub_lyric = rhyme_lyric[4:7]
will extract characters in rhyme_lyric from position 4 (included) to position 7 (not included) so the result will be cow.
You can check more on string slicing here: Python 3 introduction

re.sub replacing string using original sub-string

I have a text file. I would like to remove all decimal points and their trailing numbers, unless text is preceding.
e.g 12.29,14.6,8967.334 should be replaced with 12,14,8967
e.g happypants2.3#email.com should not be modified.
My code is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r',\d+[.]\d+', r'\d+',txt1)
print(txt1)
unless there is an easier way of completing this, how do I modify r'\d+' so it just returns the number without a decimal place?
You need to make use of groups in your regex. You put the digits before the '.' into parentheses, and then you can use '\1' to refer to them later:
txt1 = re.sub(r',(\d+)[.]\d+', r',\1',txt1)
Note that in your attempted replacement code you forgot to replace the comma, so your numbers would have been glommed together. This still isn't perfect though; the first number, since it doesn't begin with a comma, isn't processed.
Instead of checking for a comma, the better way is to check word boundaries, which can be done using \b. So the solution is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r'\b(\d+)[.]\d+\b', r'\1',txt1)
print(txt1)
Considering these are the only two types of string that is present in your file, you can explicitly check for these conditions.
This may not be an efficient way, but what I have done is split the str and check if the string contains #email.com. If thats true, I am just appending to a new list. For your 1st condition to satisfy, we can convert the str to int which will eliminate the decimal points.
If you want everything back to a str variable, you can use .join().
Code:
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt_list = []
for i in (txt1.split(',')):
if '#email.com' in i:
txt_list.append(i)
else:
txt_list.append(str(int(float(i))))
txt_new = ",".join(txt_list)
txt_new
Output:
'9,8,22,88,morris1.43#email.com,chat22.3#email.com,123,6'

Extracting a two digit number from a string in python

I need to extract a two digit number from a string in python3.
** e.g. string is "1234" and I want the middle two numbers so I get 23.**
This isn't limited to just four letters, it could be hundreds.
Please could someone help?
Thank you as always!
I have tried the following line of code and it works for me.
value = '1234'
print(value[1:-1])
Hope this helps.
Edit:
With some more char in it.
value = '1234567'
m = len(value)//2
print(value[m:m+2])
To extract two digits from the string "1234"
str function can be used.
Code:
stringparse="1234"
twodigit= stringparse[1]+stringparse[2]
print(twodigit)
Output
Out[180]: '23'
According to a quick Google search (this website), you should do:
String = "1234"
ChoppedString = String[1:3] #Remember, the first letter is 0, the second is 1, etc.
print(ChoppedString)
The [1:3] bit just means 'Start at the first letter, then get everything up to (but excluding) the second one.

Remove part of string (regular expressions)

I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'

Resources