Python basics of string handling
- 2020-05-19 05:08:52
- OfStack
Python string handling
String input:
my_string = raw_input("please input a word:")
String judgment:
(1) determine whether it is a pure letter
my_string.isalpha()
String search match:
(1) re
re regular expression instance 1: ^[\w_]*$
First, \w means match any word character including the underscore, equivalent to '[A-Za-z0-9_]'.
And then followed by a _.
Look again at the * sign: matches the previous subexpression zero or more times. For example, zo* can match "z" and "zoo". * is equivalent to {0,}.
Finally, $: indicates the end of the string, and there are no more characters.
So, what this expression means is to view this [w_] (any word character with an underscore, followed by an underscore) as a whole, appearing zero or more times!
import re
my_string = raw_input("please input a word:")
if re.match('^[a-zA-Z]$', my_string):
print "it is a word"
else:
print "it is not a word"
String transformation:
(1) convert the string to all lowercase letters.
my_string = my_string.lower()
(2) concatenate multiple strings at 1.
my_string = my_string + "abc"
(3) intercept part 1 of the string. This example removes the first and last character and intercepts the middle segment.
my_string = my_string[1:len(my_string)-1]
Thank you for reading, I hope to help you, thank you for your support of this site!