Python - Print last string after line.split - python

Is there a easy way to print the last string after you've split?
Input File:
Name:DOB:Age
Name:Name2:DOB:Age
I want the name and age...
So...
string = line.split(':')
print(string[0] + string[xxxx])
Is there anything that goes where xxxx is to always print the last string?
Thanks

string = line.split(':')
print(string[0] + string[-1])

Related

how to remove space in string list python

So i have list contains with 1 string.
biner_pass = ['00001111000000000000111111111111
00001111111111111111000011111111 11111111111100000000000000000000
11111111111111110000111111111111']
all i want is to remove the space and join all the binary.
i was trying using
binerpass = ''.join(biner_pass.split(' ')) or biner_pass.replace(" ", "") but it cannot work. so how to remove space?
The string is the 0-th element of a list with 1 element. Therefore you need
biner_pass[0].replace(" ", "")
IIUC, You can use replace.
biner_pass = ['0000111100000000000011111111111100001111111111111111000011111111 1111111111110000000000000000000011111111111111110000111111111111']
biner_pass[0] = biner_pass[0].replace(" ", "")
print(biner_pass)
Output:
['00001111000000000000111111111111000011111111111111110000111111111111111111110000000000000000000011111111111111110000111111111111']
You need to do it for each element of the list
biner_pass = [b.replace(' ','') for b in biner_pass]
binary will be a string that conatains 1 and 0 without spaces
binary = "".join(biner_pass).replace(" ", "")

New line character as user input in Python

While joining items in a list and printing them out as a string, I wanted to take user input for a character that will be used a separator. What if the separator is to be a newline? What can the user input be? Because if the user input is simply '\n' then that is being used literally ('\n' is being added as text).
Code that I ran:
tojoin = ['Hello','Its','Me','Uh','Mario']
merge = tojoin[0]
sepchar = input("Enter the character(s) with which you wish to separate the list items: ")
#User input = '\n'
for i in tojoin:
merge = merge+sepchar+i
print(merge)
Expected output:
Hello
It's
Me
Uh
Mario
Actual output:
Hello\nHello\nIts\nMe\nUh\nMario
How can I get to the expected output?
you need to add the following line of code after the input
sepchar = bytes(sepchar, "utf-8").decode("unicode_escape")
source

Format string output

With this python's code I may read all tickers in the tickers.txt file:
fh = open("tickers.txt")
tickers_list = fh.read()
print(tickers_list)
The output that I obtain is this:
A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,
Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:
["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]
Any idea?
Thanks in advance.
If you want the output to look in that format you want, you would need to do the following:
tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("["+"".join(['"' + s + '",' for s in tickers_list.split(",")])[:-1]+"]")
With the output:
["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]
Code explanation:
['"' + s + '",' for s in tickers_list.split(",")]
Creates a list of strings that contain each individual value, with the brackets as well as the comma.
"".join(...)[:-1]
Joins the list of strings into one string, removing the last character which is the extra comma
"["+..+"]"
adds the closing brackets
Another alternative is to simple use:
print(tickers_list.split(","))
However, the output will be slightly different as in:
['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']
Having ' instead of "
A solution for that however is this:
z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)
Having the correct output, by replacing that character
you can to use Split function:
tickers_list = fh.read().split(',')

Removing strings character with given input

I need to remove a certain string with the given input. For example,
user_input = input("Input File name: ")
and the user key in "patient_zero[20150203].txt" and it would like to clean up the file name by removing all instances of square brackets and the contents contained within it.
Output should be "patient_zero.txt". Is there anyway to do it?
If you just want to remove the square bracket portion of the filename, you could use:
inp = "patient_zero[20150203].txt"
output = re.sub(r'^(\S+)\[.*?\]\.(\S+)$', r'\1.\2', inp)
print(output) # patient_zero.txt
using spplit
var = "patient_zero[20150203].txt"
print(var.split("[")[0] + var.split("]")[1]) # PatientName + FileFormat
import re
s = "patient_zero[20150203].txt"
print (re.sub(r'\[[\w\s]+\]','',s))
Output:
patient_zero.txt

Python RegEx Woes

I'm not sure why this isn't working:
import re
import csv
def check(q, s):
match = re.search(r'%s' % q, s, re.IGNORECASE)
if match:
return True
else:
return False
tstr = []
# test strings
tstr.append('testthisisnotworking')
tstr.append('This is a TEsT')
tstr.append('This is a TEST mon!')
f = open('testwords.txt', 'rU')
reader = csv.reader(f)
for type, term, exp in reader:
for i in range(2):
if check(exp, tstr[i]):
print exp + " hit on " + tstr[i]
else:
print exp + " did NOT hit on " + tstr[i]
f.close()
testwords.txt contains this line:
blah, blah, test
So essentially 'test' is the RegEx pattern. Nothing complex, just a simple word. Here's the output:
test did NOT hit on testthisisnotworking
test hit on This is a TEsT
test hit on This is a TEST mon!
Why does it NOT hit on the first string? I also tried \s*test\s* with no luck. Help?
The csv module by default returns blank spaces around words in the input (this can be changed by using a different "dialect"). So exp contains " test" with a leading space.
A quick way to fix this would be to add:
exp = exp.strip()
after you read from the CSV file.
Adding a print repr(exp) to the top of the first for loop shows that exp is ' test', note the leading space.
This isn't that surprising since csv.reader() splits on commas, try changing your code to the following:
for type, term, exp in reader:
exp = exp.strip()
for s in tstr:
if check(exp, s):
print exp + " hit on " + s
else:
print exp + " did NOT hit on " + s
Note that in addition to the strip() call which will remove the leading a trailing whitespace, I change your second for loop to just loop directly over the strings in tstr instead of over a range. There was actually a bug in your current code because tstr contained three values but you only checked the first two because for i in range(2) will only give you i=0 and i=1.

Categories