join python array after splitting from given index [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a python string called line that I've split. line is a recurring string. I'm searching through an excel file and printing out each line that contains a specific word, i'll call it search which is a term that the user inputs. If the line doesn't contain search then it doesn't get printed.
I split the line, and printed out the search_index (index of the search term in the line).
s=line.split()
search_index = s.index(search) if inflected in s else "not in this line"
print(search_index)
If it doesn't exist in the line then the log will say "not in this line" instead of a number since it was crashing whe nI didn't include that.
What I awnt to do is join this split back together, but from a range with the searched term being teh middle. So, something like
new_line=[search_index - 5:search_index + 5]
but not sure if that's right since it gives me an error on the webpage of "syntax invalid"
How should this be properly done?

I think you have a typo (missing line before your range [:]) but there's another thing as well. If your search_index has been assigned a string, you can't subtract or add 5 to it.
I'm not sure of the context so you'll have to tweak this to your needs but this addresses those issues:
s=line.split()
if inflected in s:
search_index = s.index(search)
new_line = line[search_index-5:search_index+5]
else:
print("not in this line")

When you get the attribute of a list, you always have to put the name of the list before how you are calling it:
>>> line = 'hello world!'
>>> search_index = 3
>>> [search_index-3:search_index+3]
File "<stdin>", line 1
[search_index-3:search_index+3]
^
SyntaxError: invalid syntax
>>> line[search_index-3:search_index+3]
'hello '
>>>
Therefore, instead of new_line = [search_index-5:search_index+5], use new_line = line[search_index-5:search_index+5].
Here is another example:
>>> line = 'Hello this is django on python'
>>> line = line.split()
>>> search_index = line.index('django')
>>> new_line = [search_index - 2:search_index + 2]
File "<stdin>", line 1
new_line = [search_index - 2:search_index + 2]
^
SyntaxError: invalid syntax
>>> new_line = line[search_index - 2:search_index + 2]
>>> new_line
['this', 'is', 'django', 'on']
>>>

Related

How to switch \n to a newline in list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
with open("C:\\test\\data1.txt") as f:
data = f.readlines()
tail = data[-10:]
I have a file name data1.txt inside folder test, when my program reads from the file it reads the whole content from the file and prints only the last 10 lines from the file.
['this is line number 21\n', 'this is line number 22\n', 'this is line
number 23\n', 'this is line number 24\n', 'this is line number 25\n',
'this is line number 26\n', 'this is line number 27\n', 'this is line
number 28\n', 'this is line number 29\n', 'this is line number 30\n']
I want to print the last 10 lines from the file with line breaks but cant figure how I can put inside a line break inside a list data structure.
for example :
To print txt file (data1.txt) like that :
this is line number 21
this is line number 22
this is line number 23
this is line number 24
without the \n and the list deceleration ([' '])
There are many answers already, but no one explained the problem.
Problem
\n is the newline character!
Explanation
In order to be able show the newline within a string literal, the escape sequence \n is used, e.g.:
>>> 'a\nb'
'a\nb'
>>> print('a\nb')
a
b
print function prints the string, if a string argument is passed to it, but if some other object is passed to it, it first has to be converted to a string, so print(x) is the same as print(str(x)).
When a list of strings is converted to string, that is done by calling repr on each of its items:
>>> ['a', 'a\nb']
['a', 'a\nb']
>>> str(['a', 'a\nb'])
"['a', 'a\\nb']"
>>> print("['a', 'a\\nb']")
['a', 'a\nb']
Solution
Now, if you want to print the last 10 lines, it means you should print each string in the list, not the list object itself, e.g.:
for s in list_of_strings:
print(s)
Now, since the s already contains a newline and print adds a newline itself, you should remove one of the newlines to make the solution complete:
for s in list_of_strings:
print(s.strip('\n'))
or:
for s in list_of_strings:
print(s, end='')
or create one string by concatenating items of the list and print that:
print(''.join(list_of_strings))
Best is a join (works on any version):
print(''.join(tail))
Just print tail like this:
print(*tail, sep='')
The sep argument stops the automatic space that is normally used as a separator between printed items.
Maybe this will help:
f.readlines()[-10:]
this way you will get last 10 lines.
Or just:
data = f.readlines()[-10:]
for d in data:
print(d) # will print everything on new line

Why doesn't my front_back programme in Python work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The task is:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last
Below is a solution that constructs the string with first, body and last portions
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
String literals can be sliced and added:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S. str is a builtin in python, so using it as a variable name is a bad idea.
First, never call a variable str. Why? Because that is the name of the class for Python strings. If you use the same name then you loose it. I use txt.
Your test with the length is sensible, but the lower limit can be increased (a single character would be silly).
But using str.replace() is not feasible. Why? Well it could work in your test case, but only because each character is unique. str.replace() replaces every occurrence of the specified string. So if the first or last character was repeated elsewhere then that would be changed as well.
You can use slicing, where the first (leftmost) character is 0 (zero). You can also index from the right using negative numbers, so -1 is the last (rightmost) character. The range of characters goes from the start to the character after the last. So [1:-1] goes from the second character to the last but one.
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
I use return in the function, since that would be the normal way of processing text, and that is asked for in your question.

Invalid syntax error, but python fails to be helpful, as usual [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Code is as following:
cryptograph = {"a":"b", "b":"c", "c":"d", 'd': 'e', 'e':'f', 'f':'g', 'g':'h', 'h':'i', 'i':'j', 'j':'k', 'k':'l', 'l':'m', 'm':'n', 'n':'o', 'o':'p', 'p':'q', 'q':'r', 'r':'s', 's':'t', 't':'u', 'u':'v','v':'w', 'w':'x', 'x':'y', 'y':'z', 'z':'a', ' ': ' ', '.':',', ',':'.', '"':"'", "'":'"', '<':'>', '>':'<', '0':'1', '9':'2', '8':'3', '7':'4', '6':'5', '5':'6', '4':'7', '3':'8', '2':'9', '1':'0'}
def encrypt (string):
string = string.lower()
length = len(string)
toBeTranslated = splitter(string)
translated = ''
for letter in toBeTranslated:
translated = translated + cryptograph[letter]
print(translated)
def decrypt (string):
string = string.lower()
length = len(string)
toBeTranslated = splitter(string)
translated = ''
for letter in toBeTranslated:
translated = translated + list(cryptograph.keys())[list(cryptograph.values()).index[letter]
def splitter (string):
rotation = 0
stringLength = len(string)
charList = []
for _ in range(stringLength):
charList.append(string[rotation])
rotation = rotation + 1
return charList
Whenever i run it, it gives me an "invalid syntax" syntax error, but fails to show me what i did wrong.
When run in IDLE, the code is meant to encrypt and decrypt strings. I just added the decrypt function, and prior to that it worked fine (as in it encrypted things.)
I have checked indentures and colons, and found no errors.
Thanks in advance,
mrdorkface
Whenever you see this, it is usually because I have an unbalanced bracket. Just put your cursor on the character before where it said you have an error and type "]" and see if IDLE highlights code back to somewhere. There is your unbalanced bracket that is causing the error. If it doesn't highlight but instead beeps, delete the "]" and try ")" and then "}". Usually this finds your problem.
I did that and immediately found the line with the problem:
translated = translated + list(cryptograph.keys())[list(hi.values())].index[letter]
Is missing a closing "]"
A quick look says your missing some closing brackets on the line
translated = translated + list(cryptograph.keys())[list(hi.values()).index[letter]
Verify that all of your open and close brackets match up for everything.
this line is missing a bracket:
translated = translated + list(cryptograph.keys())[list(hi.values())].index[letter]

Formatting a line with spaces at the beginning

Consider below piece of code
line = "I am writing a question"
print('{0: >10}'.format(line))
This does not work as expected. I expected output to be
' I am writing a question'
I know I can achieve this by other means like printing the spaces first using one print statement and then print the sentence. But curious to know what I might be doing wrong.
Your line is longer than 10 characters; the width is a minimal value and applies to the whole column. If you wanted to add 10 spaces, always, prefix these before the format:
print(' {0}'.format(line))
If you always wanted to right-align the string in a column of 33 characters (10 spaces and 23 characters for your current line), then set the column width to that instead:
print('{0:>33}'.format(line))
Now, when your line value is longer or shorter, the amount of whitespace will be adjusted to make the output 33 characters wide again.
Demo:
>>> line = "I am writing a question"
>>> print(' {0}'.format(line))
I am writing a question
>>> print('{0:>33}'.format(line))
I am writing a question
>>> line = "question"
>>> print('{0:>33}'.format(line))
question
There is a built in method :
https://docs.python.org/2/library/stdtypes.html#str.rjust
v = 'hi'
print v.rjust(4, ' ');
prints
' hi'

Getting a word with mid frequency [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a wordlist containing numbers, English Words, and Bengali words in a column and in other column I have their frequencies. These columns have no headers. I need the words with frequencies between 5- 300. This is the code I am using. It is not working.
wordlist = open('C:\\Python27\\bengali_wordlist_full.txt', 'r').read().decode('string-escape').decode("utf-8")
for word in wordlist:
if word[1] >= 3
print(word[0])
elif word[1] <= 300
print(word[0])
This is giving me a syntax error.
File "<stdin>", line 2
if word[1] >= 3
^
SyntaxError: invalid syntax
Can anyone please help?
You should add : after your if statements to fix this SyntaxError:
wordlist = open('C:\\Python27\\bengali_wordlist_full.txt', 'r').read().decode('string-escape').decode("utf-8")
for word in wordlist:
if word[1] >= 3:
print word[0]
elif word[1] <= 300:
print word[0]
Read this:
https://docs.python.org/2/tutorial/controlflow.html
Also here it is one useful tip: when python gives you SyntaxError for some line, always look at the previous line, then at the following one.
There are few problems with your code, I add full explanation in an hour and so. See how it should look like and consult docs in the meantime:
First, it is safer to use with open() clause for opening files (see https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)
filepath = 'C:/Python27/bengali_wordlist_full.txt'
with open(filepath) as f:
content = f.read().decode('string-escape').decode("utf-8")
# do you really need all of this decdcoding?
Now content holds text from file: this is one, long string, with '\n' characters to mark endlines. We can split it to list of lines:
lines = content.splitlines()
and parse one line at the time:
for line in lines:
try:
# split line into items, assign first to 'word', second to 'freq'
word, freq = line.split('\t') # assuming you have tab as separator
freq = float(freq) # we need to convert second item to numeric value from string
if 5 <= freq <= 300: # you can 'chain' comparisons like this
print word
except ValueError:
# this happens if split() gives more than two items or float() fails
print "Could not parse this line:", line
continue

Categories

Resources