The question is simple. I have a txt file with ASCII codes that I want to display as a readable English text. In order to do so, I've parsed it into a list of integers (let's call it l) with integers. so that '\l[0]' displays '*' if l[0] = 42.
What I have trouble doing is to add an escape to the integer, for instant '\' + 'l[0]' is invalid because Python understands as "I try to escape the quote but I couldn't find the ending quote" and if I do '\'+ 'l[0]', I'll indeed see '\42' on screen, because the first backslash escapes the second and there is no escaping in the last expression.
So the question is how could one add a backslash as escape character to another string?
Thanks a lot.
Once you have converted the ASCII codes to integers, just use chr to display them.
for c in l:
sys.stdout.write(chr(c))
I think you would find chr() built-in function useful.
If you have a list of integers you can directly display corresponding ascii characters using chr() method as:
>>> l=range(33,128)
>>> for i in l: print chr(i),
...
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
This way you don't need to add '\' to any integer to display its character.
Related
I need to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.
So it should look like this
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
or
Message? pbaynatnahproarnsm
p y t h o n
I've tried this:
nim = input("Line: ")[::+3]
and it works fine, but I have to keep the spaces between the letters.
Use str.join:
nim = ' '.join(input("Line: ")[::3])
# Line: pbaynatnahproarnsm
print(nim)
Output:
'p y t h o n'
If you want to just print the letters out of sentence with spaces between them, you can use sep= parameter of print() and asterisk *:
print(*input("Line: ")[::3], sep=' ')
Prints:
Line: cxohawalkldflghemwnsegfaeap
c h a l l e n g e
Say I have a string:
"a bb c exclude_start d 3 f g h _ k l . exclude_end n 0 P exclude_start q r exclude_end s"
And say I would to apply an upper function which will return:
"A BB C exclude_start d 3 f g h _ k l . exclude_end N 0 P exclude_start q r exclude_end S"
I would like a solution which will allow for n number of excluded blocks and will apply the upper function only to the characters outside of these blocks.
It would be nice if there was a way to regex match only strings outside of the excludes, then only apply upper to these.
I'm not sure if there's a way to do this with a single regex, but here's my thought process for this. I figure we want to split the string apart so that we can capitalize only the parts that aren't in the exclude blocks. The way to do that would be to make a regex to match the exclude block:
>>> import re
>>> exclude_pattern = re.compile(r'(exclude_start.*?exclude_end)')
We need to include the question mark in there so that it doesn't match greedily.
Since we will want to keep the parts of the string that match our exclude_pattern instead of just throwing them out, we can use re.split:
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.
which is why we need the parentheses in our exclude_pattern.
Next we want to split the string using that pattern:
>>> input_string = "a bb c exclude_start d 3 f g h _ k l . exclude_end n 0 P exclude_start q r exclude_end s"
>>> exclude_pattern.split(input_string)
['a bb c ', 'exclude_start d 3 f g h _ k l . exclude_end', ' n 0 P ', 'exclude_start q r exclude_end', ' s']
That gives us the separation we need.
The next thing we want is to upper only the strings that don't match our exclude pattern. For that I figure we can map a lambda over our list that checks each entry against our exclude pattern, and only uppers the ones that don't match:
>>> list(map(lambda s: s.upper() if not exclude_pattern.match(s) else s, exclude_pattern.split(input_string)))
['A BB C ', 'exclude_start d 3 f g h _ k l . exclude_end', ' N 0 P ', 'exclude_start q r exclude_end', ' S']
The list() is just so we can see what is in the resulting map object.
After that we just join it all back together:
>>> ''.join(map(lambda s: s.upper() if not exclude_pattern.match(s) else s, exclude_pattern.split(input_string)))
'A BB C exclude_start d 3 f g h _ k l . exclude_end N 0 P exclude_start q r exclude_end S'
If you'd rather not do it as a one-liner (it's a little gross), we can make it into a function:
def excluded_upper(input_string):
exclude_pattern = re.compile(r'(exclude_start.*?exclude_end)')
split_string = exclude_pattern.split(input_string)
output = []
for s in split_string:
if exclude_pattern.match(s):
output.append(s)
else:
output.append(s.upper())
return ''.join(output)
I have a string as the result of a line.split from a file.
How can I write this string to another file starting by the 5th element?
EDIT:
I got this and it works:
for line in data.readlines ()
if not line.startswith ("H"):
s = line.split ()
finaldata.write (" ".join (s [5:]))
finaldata.write ("\n")
The only problem is that i have some empty "cells" in my input and that is messing the output (shifting the data to the left where i the original input has a blank)
How can i do it?
Thanks!
To answer the original question: If you know the element by count you should slice the string. string[5:] would print the 5th character to the end of the line. Slicing has a pretty basic syntax; lets say you have a string
a = "a b c d e f g h"
You can slice "a" from the 5th character like this
>>> a[5:]
' d e f g h'
Slicing syntax is [start:end:step] . so [5:] says start at 5 and include the rest. There are a ton of examples here Understanding Python's slice notation
The second question isn't exactly clear what you're trying to achieve... Here are some examples of common standard string manipulations with inline comments
>>> a = "a b c d e f g h"
>>> a[5] # Access the 5th element of list using the string index
' '
>>> a[5:] # Slice the string from the 5th element to the end
' d e f g h'
>>> a[5::2] # Get every other character from the 5th element to the end
' '
>>> a[6::2] # Get every other character from the 6th element to the end
'defgh'
# Use a list comprehension to remove all spaces from a string
>>> "".join([char for char in a if char != " "])
'abcdefgh'
# remove all spaces and print from the fifth character
>>> "".join([char for char in a if char != " "])[5:]
'fgh'
>>> a.strip(" ") # Strip spaces from the beginning and end
'a b c d e f g h'
>>> a[5:].strip(" ") # slice and strip spaces from both sides
'd e f g h'
>>> a[5:].lstrip(" ") # slice and use a left strip
'd e f g h'
Edit: To add in a comment from another user. if you know the character rather than the position, you can slice from that. Though, if you have duplicate characters you'll have to be careful.
>>> a[a.index("e"):] # Slice from the index of character
'e f g h'
>>> b = "a e b c d e f g h e"
>>> b[b.index("e"):]
'e b c d e f g h e'
i.e. 1->A and 26->z
I'm working on a program that is supposed to turn a letter into it's corresponding number, change the number, and then convert it back to a new letter. I've set up a dictionary that allows me to go forwards, but I am unable to convert the number back to a letter, can anyone help?
You could use a dictionary that has the number as key and the letter as value. Then conversion can be done with [num]:
>>> import string
>>> translate_dict = dict(zip(range(1, 27), string.ascii_lowercase))
>>> translate_dict[2]
'b'
Try chr(i + 96):
>>> print(*(chr(i + 96) for i in range(1, 27)))
a b c d e f g h i j k l m n o p q r s t u v w x y z
If there's a window list
text='abcdefg'
window_list=[text[i:i+3] for i in range(len(text)-3)]
print window_list
['abc', 'bcd', 'cde', 'def']
for i in window_list:
for j,k in zip(range(len(text)),i):
print j,k
0 a
1 b
2 c
0 b
1 c
2 d
0 c
1 d
2 e
0 d
1 e
2 f
i'm trying to make it so when
(j==0 and k=='c') and (j==1 and k=='d') and (j==2 and k=='e')
it would give me the starts and ending position where that occurs on the string text
so it would give me
[2-4]
Have you thought to do it in this way?
>>> text='abcdefg'
>>> window_list=[text[i:i+3] for i in range(len(text)-3)]
>>> ["-".join([str(i),str(i+len(w))]) for i,w in enumerate(window_list) if w == 'cde'] #for single item
['2-5']
>>> ["-".join([str(i),str(i+len(w))]) for i,w in enumerate(window_list) if w in ['cde','def']] # for multiple items
['2-5', '3-6']
>>>
Note: enumerate the list and search for those items which matches the condition. Return the index followed by the end position (which is index + length of the sub-sequence). Please note, the result would be a string rather than what you are expecting.
import re
seq = 'abcdefabcdefabcdefg'
for match in re.finditer('abc', seq):
print match.start(), match.end()
Logic:
All you need to do is find if your pattern is in the doc or not. This can be done easily using Python in built string "find" function. Once you find the start position of your string, then all you need to do is add the length of your pattern to get end position. thats it! job done ;)
The Code:
text = "abcdefghifjklmnopqrstuvwxyz"
start_position = text.find("abc")
if(start_position>-1):
end_position = start_position+len(start_position) - 1
else:
print "Pattern not found"
print start_position, "-", end_position
The Output:
0 - 2
Reference:
Check Official Python String Functions Documentation