我试图弄清楚看起来应该很简单的事情。我试图从名称中删除中间的首字母,但我不知道如何在不为字母表的每个字母创建replace()的情况下执行此操作。这就是我正在寻找的:
(开始时)
" John D Smith"
" Robert B Johnson"
(结束)
" John Smith"
"罗伯特约翰逊"
在Python中完成上述操作的最简单方法是什么?中间的首字母是随机的,但总是被白色空间包围。
答案 0 :(得分:3)
根据您的帖子提供此帮助
>>> import re
>>> re.sub(' [A-Z]* ', ' ', "John D Smith")
'John Smith'
>>> re.sub(' [A-Z]* ', ' ', "Robert B Johnson")
'Robert Johnson'
答案 1 :(得分:0)
value
答案 2 :(得分:0)
内置字符串操作非常简单。
name = "Name N Name".split() # Splits string at whitespace into list
del name[1] # Deletes 2nd item (middle initial)
removed_middle_initial = " ".join(name) # "Name Name"
这假设名字和姓氏不包含任何空格字符。如果需要更高级的要求,那么显然需要处理这些条件。
答案 3 :(得分:0)
(?=)
展望未来。 [A-Z]
首字母为1个字母。
import re
re.sub(' [A-Z](?= )', '', "John D Smith")
答案 4 :(得分:0)
您可以使用sub
方法将中间的首字母替换为空格。
#import <Foundation/Foundation.h>
#import "gmail.h"
static NSString *const kKeychainItemName = @"Gmail API";
static NSString *const kClientID = @"this is my key";
@implementation gmail
@synthesize service = _service;
@synthesize output = _output;
// When the view loads, create necessary subviews, and initialize the Gmail API service.
- (void)viewDidLoad {
[super viewDidLoad];
// Create a UITextView to display output.
self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
self.output.editable = false;
self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.output];
// Initialize the Gmail API service & load existing credentials from the keychain if available.
self.service = [[GTLServiceGmail alloc] init];
self.service.authorizer =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:nil];
}
// When the view appears, ensure that the Gmail API service is authorized, and perform API calls.
- (void)viewDidAppear:(BOOL)animated {
if (!self.service.authorizer.canAuthorize) {
// Not yet authorized, request authorization by pushing the login UI onto the UI stack.
[self presentViewController:[self createAuthController] animated:YES completion:nil];
} else {
[self fetchLabels];
}
}
// Construct a query and get a list of labels from the user's gmail. Display the
// label name in the UITextView
- (void)fetchLabels {
self.output.text = @"Getting labels...";
GTLQueryGmail *query = [GTLQueryGmail queryForUsersLabelsList];
[self.service executeQuery:query
delegate:self
didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}
- (void)displayResultWithTicket:(GTLServiceTicket *)ticket
finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
error:(NSError *)error {
if (error == nil) {
NSMutableString *labelString = [[NSMutableString alloc] init];
if (labelsResponse.labels.count > 0) {
[labelString appendString:@"Labels:\n"];
for (GTLGmailLabel *label in labelsResponse.labels) {
[labelString appendFormat:@"%@\n", label.name];
}
} else {
[labelString appendString:@"No labels found."];
}
self.output.text = labelString;
} else {
[self showAlert:@"Error" message:error.localizedDescription];
}
}
// Creates the auth controller for authorizing access to Gmail API.
- (GTMOAuth2ViewControllerTouch *)createAuthController {
GTMOAuth2ViewControllerTouch *authController;
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeGmailReadonly, nil];
authController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:[scopes componentsJoinedByString:@" "]
clientID:kClientID
clientSecret:nil
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)];
return authController;
}
// Handle completion of the authorization process, and update the Gmail API
// with the new credentials.
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)authResult
error:(NSError *)error {
if (error != nil) {
[self showAlert:@"Authentication Error" message:error.localizedDescription];
self.service.authorizer = nil;
}
else {
self.service.authorizer = authResult;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
// Helper for showing an alert
- (void)showAlert:(NSString *)title message:(NSString *)message {
UIAlertView *alert;
alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
@end
这是使用>>> re.sub("\s[A-Za-z]\s", " ", "John D Smith")
John Smith
字母字符类来查找由空格包围的第一个单个字母。然后用一个空格替换整个3个字符的字符串(空格,字母,空格)。