Reverse a string in Python

Using slicing: >>> ‘hello world'[::-1] ‘dlrow olleh’ Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, “repeatedly step from right to left by 1 character”.

Random string generation with upper case letters and digits

Answer in one line: ”.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) or even shorter starting with Python 3.6 using random.choices(): ”.join(random.choices(string.ascii_uppercase + string.digits, k=N)) A cryptographically more secure version: see this post ”.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) In details, with a clean function for further reuse: >>> import string >>> import random >>> … Read more

startsWith() and endsWith() functions in PHP

PHP 8.0 and higher Since PHP 8.0 you can use the str_starts_with Manual and str_ends_with Manual Example echo str_starts_with($str, ‘|’); PHP before 8.0 function startsWith( $haystack, $needle ) { $length = strlen( $needle ); return substr( $haystack, 0, $length ) === $needle; } function endsWith( $haystack, $needle ) { $length = strlen( $needle ); if( … Read more

How do I create a Java string from the contents of a file?

Read all text from a file Java 11 added the readString() method to read small files as a String, preserving line terminators: String content = Files.readString(path, StandardCharsets.US_ASCII); For versions between Java 7 and 11, here’s a compact, robust idiom, wrapped up in a utility method: static String readFile(String path, Charset encoding) throws IOException { byte[] … Read more

How to check if a string “StartsWith” another string?

You can use ECMAScript 6’s String.prototype.startsWith() method, but it’s not yet supported in all browsers. You’ll want to use a shim/polyfill to add it on browsers that don’t support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use … Read more

How do I split a string in Java?

Use the appropriately named method String#split(). String string = “004-034556”; String[] parts = string.split(“-“); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556 Note that split‘s argument is assumed to be a regular expression, so remember to escape special characters if necessary. there are 12 characters with special meanings: the backslash \, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)