append int ordinal to str in Python 2.7 - python-2.7

How can I append an int containing an ordinal number to a str in Python 2.7?
Example:
number = 10 # You can assume its smaller than 128
mystr = "abc"
mystr = mystr+number # Gives error
assert mystr == "abc\x0A"
Of course, "mystr%d"%number or mystr+str(number) won't work, they would give "abc10"

I think you want the built-in function chr:
number = 10
mystr = "abc"
mystr = mystr + chr(number)

import struct
mystr = mystr+struct.pack("b",number)
satisfies the assertion.

Related

Trim String/Text in Flutter

Hi I tried to trim a link in flutter
Currently I am looking into regexp but I think that is not possible
This is the link in full:
http://sales.local/api/v1/payments/454/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH
What I am trying to do is to trim the link like this:
http://sales.local/api/v1/payments/454
Kindly advise on best practise to trim string/text in flutter. Thanks!
try to use substring() :
String link = 'http://sales.local/api/v1/payments/454/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH';
String delimiter = '/ticket';
int lastIndex = link.indexOf(delimiter);
String trimmed = link.substring(0,lastIndex);
//print(trimmed);
input string print for Flutter:
String str2 = "-hello Friend- ";
print(str2.trim());
Output Print : -hello Friend-
NOte: Here last space remove from string.
1.Right Method:
var str1 = 'Dart';
var str2 = str1.trim();
identical(str1, str2);
2.Wrong Method
'\tTest String is Fun\n'.trim(); // 'Test String is Fun'
main(List<String> args) {
String str =
'http://sales.local/api/v2/paymentsss/45444/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH';
RegExp exp = new RegExp(r"((http|https)://sales.local/api/v\d+/\w.*?/\d*)");
String matches = exp.stringMatch(str);
print(matches); // http://sales.local/api/v2/paymentsss/45444
}

Extracting a required string form a string stored in txt file

I have the below information in a txt file which is of 300lines
5.2.7.1 timer value ($D125)
5.2.7.2 Power back information ($05B2)
5.2.7.3 Time Since power off ($05B4)
5.2.7.4 highspeed mode State ($0730)
I want the below information to be read and stored two different strings
For Example
str1 = timer value
str2 = D125
Need a PYTHON Script , compatible with PYTHON 2.7.5.
I am also new to python and have no experience, but I managed to develop the code below which is not the best code possible, but I guess the output is exactly what you want:
import re
f = open('a.txt').readlines()
str1 = []
str2 = []
for i in f:
res = re.sub("\n", '', i)
res = re.sub("\d.\d.\d.\d ", "", res)
str = re.split("\(\$", res)
str[1] = re.sub("\)", '', str[1])
str1.append(str[0])
str2.append(str[1])
print(str1)
print(str2)
As #Milind mentioned, RegEx could help you find patterns.
I assumed that txt file's name as a.txt.
str_1= str[str.find(start_str)+len(start_str):str.rfind(end_str)]
All you have to do is initialise start_str = "XXXXXXX" and end_str = "YYYYY".

How can I split certain phrase a String?

I have String with some search items and I want to split them in an array of String.
Example:
String text = "java example \"this is a test\" hello world";
I want to get the following results
result[0] = "java";
result[1] = "example";
result[2] = "\"this is a test\"";
result[3] = "hello";
result[4] = "world";
In short, I want to combine text.split(" ") and text.split("\"");
Is there an easy way to code it?
Thanks!
You can use this regex in String#split method:
(?=(([^\"]*\"){2})*[^\"]*$)\\s+
Code:
String text = "java example \"this is a test\" hello world";
String[] tok = text.split("(?=(([^\"]*\"){2})*[^\"]*$)\\s+");
// print the array
System.out.println( Arrays.toString( arr ) );
Output:
[java, example, "this is a test", hello, world]
This regex should match (\\".+?\\")|([^\s]+)
It matches anything within \" including the \" OR single words.
Check here for results: http://www.regexr.com/399a4
I think you are a bit confused and there are errors in your code!
Composing your string should be:
String text = "java example \"this is a test\" hello world";
The value of the variable text would then be:
java example "this is a test" hello world
I am rather assuming that you want to extract this into the following array:
result[0] = "java";
result[1] = "example";
result[2] = "\"this is a test\"";
result[3] = "hello";
result[4] = "world";
You can do this by using a regular expression, for example:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String data = "java example \"this is a test\" hello world";
Pattern p = Pattern.compile("((?:\"[a-z\\s]+\")|[a-z]+)");
Matcher m = p.matcher(data);
List<String> lst = new ArrayList<String>();
while(m.find()) {
lst.add(m.group(1));
}
String[] result= new String[lst.size()];
result = lst.toArray(results);
for(String s: result) {
System.out.println(s);
}
}
}
The regular expression ((?:\"[a-z\\s]+\")|[a-z]+) will match on either:
1) sequences of characters a to z or whitespace between double quotes
2) sequence of characters a to z.
We then extract these matches using m.find

Python letter swapping

I'm making a program that scrambles words for fun and I've hit a roadblock. I am attempting to switch all the letters in a string and I'm not quite sure how to go about it (hello = ifmmp). I've looked all around and haven't been able to find any answers to this specific question. Any help would be great!
You want a simple randomized cypher? The following will work for all lowercase inputs, and can easily be extended.
import random
import string
swapped = list(string.lowercase)
random.shuffle(swapped)
cipher = string.maketrans(string.lowercase, ''.join(swapped))
def change(val):
return string.translate(val, cipher)
You can probably modify this example to achieve what you need. Here every vowel in a string is replaced by its vowel position:
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
# this is the output
"th3s 3s str3ng 2x1mpl2....w4w!!!"
Try maketrans in combination with the string.translate function. This code removes letters from your word from the letters you are scrambling with first. If you just want lowercase only use string.lowercase instead of string.letters.
>>> import string, random
>>> letters = list(string.letters)
>>> random.shuffle(letters)
>>> letters = "".join(letters)
>>> word = 'hello'
>>> for letter in word:
... letters = letters.replace(letter, '')
...
>>> transtab = string.maketrans(word, letters[:len(word)])
>>> print word.translate(transtab)
XQEEN
The "scrambling" you appear to be after is called Caesar's cipher, with a right shift of 1. The following Python will achieve what you're after:
def caesar(str):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
# Move the last 1 chars to the start of the string
toalpha = fromalpha[1:] + fromalpha[:1]
# Make it work with capital letters
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)
If you're interested in the general case, this function will do the job. (Note that it is conventional to express Caesar ciphers in terms of left shifts, rather than right.)
def caesar(str, lshift):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
toalpha = fromalpha[-lshift:] + fromalpha[:-lshift]
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)

Removing 3 specific characters, if present from the start of a string VB.net

I have a situation where I need remove a prefix from a string, if it exists.
Dim str As String = "samVariable"
Needs to be converted to Variable
Easy, with TrimStart
str = str.trimstart("s"c, "a"c, "m"c)
Except...
The string might not always start with "sam"
Example:
Dim str As String = "saleDetails"
This will now become aleDetails
Which is wrong, so how about Replace
str = str.Replace('sam','')
Brilliant! Now:
Example 1:
Dim str As String = "samVariable"
str = str.Replace('sam','')
str = "Variable"
Example 2:
Dim str As String = "saleDetails"
str = str.Replace('sam','')
str = "saleDetails" (unaffected)
BUT....
What if:
Dim str As String = "Resample"
str = str.Replace('sam','')
str = "Reple"
This is wrong again!
So, my question is:
How do I remove "sam" from the beginning of a string only?
I had expected TrimStart("sam") to work, but it doesn't
if str.StartsWith("sam")
str = str.Substring(3)
end if
Not a one-liner, but easy to follow.
str = New Regex("^sam").Replace(str, String.Empty)
The regular expression looks for sam at the start of the string and replaces it with empty, effectively removing the sam from the beginning.
EDIT Per Konrad's comment, the shared method call would be better:
str = Regex.Replace(str, "^sam", String.Empty)